1

I'll link my code here. I don't understand why it's giving me this error from time to time while i shoot at enemies. The code uses the p5.js library.

Any help would be appreciated!

function draw(){

  background(160);

   for(var i in enemies){
   enemies[i].show();
   enemies[i].move();
   for(var j in bullets){
     if(enemies[i].isHit(bullets[j])){
       bullets.splice(j,1);
       enemies.splice(i,1);
     }
   }
 }

 for(var i in bullets){
    bullets[i].show();
    bullets[i].move();
 }

 pg.show();

}

Here is the function that gets updated every frame, and there's the enemy isHit function (placed in the constructor of Enemy)

    this.isHit=function(a){
    d=dist(this.x,this.y,a.x,a.y);
    if(d<12.5){
      return true;
    }
    else {
      return false;
    }
  }    

If you need anything else, i'm here at your disposal!

Aouf
  • 11
  • 1
  • 1
    See [Remove items from array with splice in for loop](http://stackoverflow.com/q/16217333/669576) – 001 Dec 28 '16 at 22:27
  • for in loops over an array is a bad idea. Error is saying enemies[i] is undefined do to you removing items.... Think about it as blocks. You remove one from the bottom, all the others shift down a spot. – epascarello Dec 28 '16 at 22:31
  • If the *last* enemy was hit and removed via `enemies.splice(i,1);` but there are still bullets to check, then `enemies[i]` will be `undefined` in the next iteration of `bullets`. Simple example: `var a = [1,2,3]; a.splice(2, 1); console.log(a[2]); // undefined`. You probably want to stop iterating over `bullets` after the enemy was removed. – Felix Kling Dec 28 '16 at 22:32

0 Answers0