0

I have a function that spawns enemies in my game. It creates a new object which is a duplicate of the "blueprint" for the enemy. I then have it insert the x and y coordinate passed to the function, and finally I insert it into an array containing all the enemies that are alive.

The problem is that every x and y coordinate of enemies in the enemy array will inherit the last coordinates passed to the spawn function.

// Enemy array
var enemy = [];

// The blueprint to use when creating enemies
var enemy_1 = {
 
 id: "enemy",
 
 width: 40,
 height: 40,
 health: 1000,
 color: "orange",
 
 velocity: {
  
  x: 0,
  y: 0,
  max: 4,
  min: 0.5,
  inc: 0.2,
     friction: 0.2
  
 },
 
 projectile: {
  
  amount: 1, // 1, 3, 5 ... odd numbers
  offsetStartTimes: 1, // x >= 1 // NOT 0 = STACKED SHOOTS
  offsetAngle: 0, // Deg
  speed: 4,
  delay: 0.8, // Seconds
  duration: 0.5, // Seconds
  color: "red",
  damage: 20,
  last: 0 // Last time a projectile was shot
  
 },
 
 instruction : {
  
  attackDist: 500
  
 }
 
};

function spawn_enemy( x, y, blueprint){
 
 
 // Duplicate the blueprint object
 var newEnemy = blueprint;
 newEnemy.x = x;
 newEnemy.y = y;
 
 
 // Add it to the array
 enemy.push(newEnemy);
 
 //DEBUG
 console.log(enemy);
}


spawn_enemy(20, 50, enemy_1);
spawn_enemy(50, 50, enemy_1);
spawn_enemy(100, 50, enemy_1);

Full game at http://swiftpeak.net/

Source code at https://github.com/JohanSundman/JohanSundman.github.io

moopet
  • 6,014
  • 1
  • 29
  • 36
Johan Sundman
  • 175
  • 2
  • 15
  • 2
    With ```var newEnemy = blueprint;``` you store the reference from your ```blueprint``` (```enemy_1```) in ```newEnemy```. Therefore, all changes are actually made to ```enemy_1```. Instead you need to make a copy of the object, like in [this question](http://stackoverflow.com/a/728694/7028020) – Dario Oct 24 '16 at 10:54
  • 1
    They all reference the same object. Look into Object.assign – rlemon Oct 24 '16 at 10:55

1 Answers1

0

To clone the object, you need to use Object.assign function like this:

var obj = { a: 1 };
var copy = Object.assign({}, obj);

More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

This page also has polyfill if you need one.

In you case, you should

var newEnemy = Object.assign({}, blueprint};
Deividas
  • 6,437
  • 2
  • 26
  • 27