1

Probably just something dumb but I'm rewriting Galaga in p5.js for a university assignment and towards the beginning I'm at destroying enemies. When a bullet is fired and it hits say the third enemy on the screen, all of the enemies before it are being destroyed.

The enemies array is just a simple array where enemy objects are pushed: enemies = [];

The destroy function for the enemies is

this.die = function() {
    enemies.splice(enemies[this.index], 1);
}

And the loop is

for( var b = 0; b < player.bullets.length; b++) {
    for(var i = 0; i < enemies.length; i++) {
        var bullet = player.bullets[b];
        if(collision(bullet.x, enemies[i].x, bullet.y, enemies[i].y, 20, 55, 40, 55)) {
            enemies[i].die();
        }
    }
}

Any help would be great

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
J.Smart
  • 13
  • 2
  • 1
    What's exactly the question here ? – Denys Séguret Sep 23 '19 at 08:45
  • not remove (.splice()) the destroyed element, but replace it by another value that not shown into screen – Sim1-81 Sep 23 '19 at 08:47
  • What does `enemies[this.index]` return? If it's not a number then it's not going to react properly. Also don't forget that looping beginning to end, once you splice, you are changing the size of the array, incrementing `i` causing a skip. eg, if `i` was 3 and you delete index 3, what was at index 4 is now 3 but you increment `i` to 4 without checking the new 3. Either go from end to beginning or decrement `i` when you splice to supplement the upcoming increment. – Matt Sep 23 '19 at 10:20
  • Does it work if you do `enemies.splice(i, 1);` instead of `enemies[i].die();`? – Rabbid76 Sep 23 '19 at 13:13

1 Answers1

0

The parameters to splice are the start index (the first elment) which has top be deleted and the number of elements.

So the statement

enemies.splice(enemies[this.index], 1);

doesn't seem to be correct at all. Possibly the statement

enemies.splice(this.index, 1);

would do what you want, if this.index would be the index of the enemy in the array. But that won't be the case, if you've delete a previously arranged enemy from the array.

I recommend to do enemies.splice(i, 1); instead of enemies[i].die();:

for( var b = 0; b < player.bullets.length; b++) {
    for(var i = 0; i < enemies.length; i++) {
        var bullet = player.bullets[b];
        if(collision(bullet.x, enemies[i].x, bullet.y, enemies[i].y, 20, 55, 40, 55)) {
            enemies.splice(i, 1);
        }
    }
}

Note, once an element was removed from the list, the the attribute .index of the following elements hast to be updated.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174