gpt4 book ai didi

javascript - 崩溃碰撞时数组拼接多个对象

转载 作者:行者123 更新时间:2023-12-03 00:47:33 26 4
gpt4 key购买 nike

我目前正在开发一个基本的 html 和 javascript 游戏,我遇到了一个困境。当我的子弹(存储为数组)与 myObstacles(也存储为数组)碰撞时,有时我击中的障碍物会被拼接,有时会拼接多个障碍物。这是我的崩溃碰撞代码

 this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright <
otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}

这是当子弹击中敌人时我如何拼接障碍物

   for (y = 0; y < myObstacles.length; y += 1) {
if (myGamePiece.crashWith(myObstacles[y])) {
var ctx = myGameArea.context;
ctx.fillText("Game Over", 150, 150);
myGameArea.stop();

}

for (i = 0; i < bullets.length; i += 1) {

if(myObstacles[y].crashWith(bullets[i])) {
myObstacles.splice(myObstacles[y], 1);

}
}
}

我们将非常感谢一些帮助。

要查看完整代码,我创建了 github repository

最佳答案

Array.splice() 删除从给定索引开始的给定数量的元素,所有剩余元素向下移动。然后 for 循环的事后 block 将 i 加 1。这样就跳过了索引。

看看这个截图:

    let fiboArray  = [ 1, 1, 2, 3, 5, 8 ];

// Lets say we want to remove all 1 of fiboArray
// Array.splice() fails in forward for loop
for (let i = 0; i <= fiboArray.length ; i++) {
if (fiboArray[i] === 1) {
fiboArray.splice(i, 1);
}
}
console.log(fiboArray);
// → [ 1, 2, 3, 5, 8 ] but expected was [ 2, 3, 5, 8]
// Thats because the remaining elements shift down

let fiboArray2 = [ 1, 1, 2, 3, 5, 8 ];

// Array.splice() with backward for loop
for (let i = fiboArray2.length - 1; i >= 0; i--) {
if (fiboArray2[i] === 1) {
fiboArray2.splice(i, 1);
}
}
console.log(fiboArray2);
// → [ 2, 3, 5, 8 ]

// Or decrement `i` in a forward for-loop after call `splice(i--, 1)`;

关于javascript - 崩溃碰撞时数组拼接多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53179766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com