I don’t know what I’m missing… the full code is pretty big so I’ll just put the part throwing exceptions here.
for (int i = 0; i < player.getBullets().size(); i++) { //for every player bullet
for (int j = 0; j < aliens.getAliens().size(); j++) { //for every player bullet every alien
player.getBullets().get(i);
aliens.getAliens().get(j);
if (player.getBullets().get(i).getBounds().intersects(aliens.getAliens().get(j).getBounds())){ //player bullet vs alien collison
if (aliens.getAliens().get(j).getType() == 1)
score += 2 + level;
else if(aliens.getAliens().get(j).getType() == 2)
score += 4 + level;
else
score += 8 + level*2;
aliens.getAliens().remove(j); // alien dies
player.getBullets().remove(i);
System.out.println("player bullet removed");
}
}
}
It threw an exception on the //player bullet vs alien collision line.
I added in player.getBullets().get(i) and the getAliens() to figure which one threw the exception and it was the player one.
Error seems kind of random, but I believe it goes out of bounds when an alien moves sideways onto a bullet. It works fine if the bullet hits the alien straight on. Could this be an error with using intersects?
By the way, this is a Space Invaders mimic. Any help would be appreciated.
You’re altering your lists as you’re traversing them (by calling
.remove()inside the loop). You’re deleting the bullet in the middle of checking for collisions with it.One solution is to give aliens/bullets/other such objects an
isDeadvariable. Then, instead of deleting them inside the loop, wait until after the loop and delete everyone withisDead == true.