Multiple objects in array splicing when crash collision occurs

4009 views javascript
-3

I am currently working on a basic html and javascript game and I have encountered a dilemma. When my bullets (which are stored as an array) collide with myObstacles(also stored as an array) sometimes the obstacle that I hit is spliced and other times multiple are spliced. Here is my crash collision code

 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;
      }

Here is how I am splicing the obstacle when a bullet hits an enemy

   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);

   }
 }
}

Some help would be very appreciated.

To see the full code I made a github repository

answered question

1 Answer

4

Array.splice() remove a given number of elements starting at a given index and all the remaining elements shift down. Then the afterthought block of the for-loop increments i by 1. So that a index is skipped.

Take a look at this snipped:

    let fiboArray  = [ 1, 1, 2, 3, 5, 8 ];
    
    // 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 ]
    
    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 ]

posted this

Have an answer?

JD

Please login first before posting an answer.