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