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); if(asteroids.get(j).intersects(bullet)) { // 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); asteroids.get(j).setLocation(-asteroids.get(j).width, -asteroids.get(j).height); status.setNewAsteroid(true); lastAsteroidTime = System.currentTimeMillis(); // play asteroid explosion sound soundMan.playAsteroidExplosionSound(); // remove bullet bullets.remove(i); break; } } }
Thank you all very much.