【发布时间】:2014-06-04 20:38:23
【问题描述】:
我正在创建一个在画布上随机显示圆圈的游戏。圆圈对象被添加到一个数组中,每当玩家与其中一个发生碰撞时,我都想删除该对象。这是我目前用于碰撞的代码 -
for(var i = 0; i < currentGame.items.length; i++)
{
if (player1.x < currentGame.items[i].x + currentGame.items[i].radius*2 && player1.x + currentGame.items[i].radius*2 > currentGame.items[i].x &&
player1.y < currentGame.items[i].y + currentGame.items[i].radius*2 && player1.y + player1.car.height > currentGame.items[i].y) {
currentGame.score++;
position = currentGame.items.indexOf(i);
currentGame.items.splice(position, 1);
}
}
当玩家点击已添加到数组/画布的最后一个圆圈时,此代码可以正常工作。但是,如果玩家击中了数组中间的圆圈,那么数组的所有后续项也将被删除(而不是之前的项)。玩家得分将增加,但有多少圈子被删除。这表明,当其中一个圆圈被移除时,项目会向下移动并取代刚刚删除的项目,包括获取它的位置坐标,以便玩家与所有圆圈发生碰撞,然后将它们全部删除。
我不知道如何解决这个问题,或者我是否错误地使用了拼接。
这是我添加到数组的代码 -
function createItem(){
item1 = new itemSmall();
item1.x = Math.floor(Math.random()*((currentGame.windowWidth - 40)-40+1)+40);
item1.y = Math.floor(Math.random()*((currentGame.windowHeight - 40)-40+1)+40);
item1.fillStyle = "rgb(200,80,200)";
item1.lineWidth = 4; //Stroke Thickness
item1.strokeStyle = "rgb(255,215,0)";
currentGame.items.push(item1);
}
项目存储在这里(为了清楚起见,我从该对象中删除了所有其他内容)-
function gameValues(){
this.items = [];
}
currentGame = new gameValues();
【问题讨论】:
-
console.log 在循环时记录对象,你会明白为什么
标签: javascript arrays splice