由于某种原因,当试图将中间索引从数组、敌人中拼接时,最后一个元素将被移除。我问过几个人,但他们不知道问题出在哪里。
如果我向第五个敌人发射子弹,数组的最后一个元素就会被拼接,而不是索引5。
enemies.forEach(function(element, index){
for(var i = 0; i < bullets.length; i++) {
if(bullets[i].X + 5 > element.X && bullets[i].X < element.X+30 &&
bullets[i].Y + 5 > element.Y && bullets[i].Y < element.Y+30){
//These conditions look messy but they work
console.log(index); //This Outputs the Correct Index
enemies.splice(index, 1); //<- Splices The Last Index instead of a specific one
bullets.splice(i, 1);
}
}
})这个链接有我的全部代码的副本和这个函数https://pastebin.com/Q7swAh1a的备用版本。
发布于 2018-03-18 18:48:10
你的问题是:
for(var i = 0; i < enemies.length; i++) {
enemies[i].Draw((66*i)+18, 50, i);//Here is the bug
enemies[i].Move();
}还有这里
this.Draw = function(x, y, i) {
this.X = x;//These 2 lines overwrite the real positions
this.Y = y;
ctx.fillStyle = 'orange';
ctx.fillRect(this.X, this.Y, 30, 30);
ctx.fillStyle = 'white';
ctx.fillText(i, this.X, this.Y);
}您根据敌人在数组中的索引而不是他们自己的位置绘制敌人。
这应该是可行的:
for(var i = 0; i < enemies.length; i++) {
enemies[i].Draw(i);
enemies[i].Move();
}
this.Draw = function(i) {
ctx.fillStyle = 'orange';
ctx.fillRect(this.X, this.Y, 30, 30);
ctx.fillStyle = 'white';
ctx.fillText(i, this.X, this.Y);//i would be the index in the array and changes with splice()
}https://stackoverflow.com/questions/49351467
复制相似问题