Working differently with array elements in the same loop?
Hey guys. I have a question to see if anyone could help me. I have this classic Asteroid game where asteroids keep falling down and a little ship destroys them with bullets. The asteroids are stored in an ArrayList. There is a for loop in that checks if an asteroid and a bullet collide. If they do, the loop erases the asteroid.
My problem is that when the bullet does collide one of the asteroids, the hit asteroid does erase, but the other two get deleted as well, even though they show up again quickly. How do I make it so that if a certain element of the array gets hit, only that element gets erased and not the other ones?
Here is the code in case anyone wants to see it directly.
// check bullet-asteroid collisions
for(int j = 0; j <= asteroids.size() - 1; j++)
for(int i=0; i<bullets.size(); i++)
Bullet bullet = bullets.get(i);
// increase asteroids destroyed count
status.setAsteroidsDestroyed(status.getAsteroidsDestroyed() + 1);
// "remove" asteroid
asteroidExplosion = new Rectangle(asteroids.get(j).x,asteroids.get(j).y,asteroids.get(j).width,asteroids.get(j).height);
lastAsteroidTime = System.currentTimeMillis();
// play asteroid explosion sound
// remove bullet
Thank you all very much.
Re: Working differently with array elements in the same loop?
How do you know that two others get deleted? Are you sure that it isn't a problem with the shifting of positions in the list because an element has been removed?
the hit asteroid does erase, but the other two get deleted as well
Try debugging the code by printing out the contents of the ArrayList before and after an item is removed from the list so you can see what is happening to the list.
If you start at the end of the list and go towards the beginning, removing an element won't shift the position of the elements remaining to be looked at.
Otherwise: Can you make a small testing program the compiles, executes and shows the problem?