【发布时间】:2016-10-24 10:51:05
【问题描述】:
我有一个在我的游戏中生成敌人的功能。它创建了一个新对象,该对象是敌人“蓝图”的副本。然后我让它插入传递给函数的 x 和 y 坐标,最后我将它插入到一个包含所有活着的敌人的数组中。
问题是 每个敌人数组中敌人的 x 和 y 坐标都会继承最后传递给 spawn 函数的坐标。
// 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);
【问题讨论】:
-
使用
var newEnemy = blueprint;,您将来自blueprint(enemy_1) 的引用存储在newEnemy中。因此,所有更改实际上都是针对enemy_1进行的。相反,您需要制作对象的副本,例如 this question -
它们都引用同一个对象。查看 Object.assign
标签: javascript arrays object