【问题标题】:JS value applies to every object in an arrayJS 值适用于数组中的每个对象
【发布时间】: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);

完整游戏http://swiftpeak.net/

源代码https://github.com/JohanSundman/JohanSundman.github.io

【问题讨论】:

  • 使用var newEnemy = blueprint;,您将来自blueprint (enemy_1) 的引用存储在newEnemy 中。因此,所有更改实际上都是针对enemy_1 进行的。相反,您需要制作对象的副本,例如 this question
  • 它们都引用同一个对象。查看 Object.assign

标签: javascript arrays object


【解决方案1】:

要克隆对象,你需要像这样使用Object.assign函数:

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

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

如果你需要的话,这个页面也有 polyfill。

在你的情况下,你应该

var newEnemy = Object.assign({}, blueprint};

【讨论】:

    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 2020-08-11
    • 2017-11-25
    • 1970-01-01
    相关资源
    最近更新 更多