发生崩溃冲突时数组拼接中的多个对象

时间:2018-11-06 20:45:48

标签: javascript canvas

我目前正在开发基本的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

1 个答案:

答案 0 :(得分:1)

Array.splice()删除从给定索引开始的给定数量的元素,所有其余元素向下移动。然后for-loop的事后程序块将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)`;