As a preface, I have searched the forums but found nothing relating to my specific situation. I just started learning Java about a week ago, and this is my first foray into object oriented programming.
I'm building a basic game (think somewhat like Space Invaders when it comes to mechanics). I have a "Projectile" class, a "FallingThings" class (which is the parent class to the classes I have for objects falling down (Money, Friend, Enemy)). Each projectile that is shot is stored in an ArrayList, and as is every instance of Money, Friend, and Enemy (each in their own ArrayList).
The problem happens when I implement collision detection. First off, it takes multiple bullets to make the collision mechanism work (I think I might have just messed up some numbers here but I'm not 100% sure). Now, sometimes after I fire multiple bullets (and they are long gone), a collision is detected without me firing another bullet and a FallingThings object disappears from the screen. Also, at other times, multiple objects disappear at once. The weirdest thing is that all this is inconsistent, and not always reproducible in the same fashion. However, my collisions with the player character work perfectly.
Anyone have some ideas as to how I can fix this? My code is below:
Method in the "FallingThings" class (the ArrayLists are defined in the StartingClass (the main class)).
public void checkBulletCollision(Rectangle rectangle) {
for (int j = 0; j < Character.getProjectiles().size(); j++) {
Projectile p = (Projectile) Character.getProjectiles().get(j);
if (p.isVisible() == true) {
for (int i = 0; i < StartingClass.getMoneys().size(); i++) {
Money m = (Money) StartingClass.getMoneys().get(i);
if (m.getR().intersects(rectangle)) {
m.remove(i);
System.out.println("bullet collision");
}
}
for (int i = 0; i < StartingClass.getEnemies().size(); i++) {
Enemy e = (Enemy) StartingClass.getEnemies().get(i);
if (e.getR().intersects(rectangle)) {
e.remove(i);
}
}
for (int i = 0; i < StartingClass.getFriends().size(); i++) {
Friend f = (Friend) StartingClass.getFriends().get(i);
if (f.getR().intersects(rectangle)) {
f.remove(i);
}
}
}
}
}
My update method for projectiles:
public void update() {
y -= speedY;
if (y < 0) {
visible = false;
}
rectangle.setBounds(getRectangle());
}
I've been trying to fix this for the entire day, and still can't get a proper implementation. I have tried using ListIterator, but that caused the program to freeze and a typecasting error to be thrown.
Thank you so much for the help! =)
I suspect you are having problems because you are removing items from the list by index while looping over that list. Removing items causes the index counter to get out of allignment. Try use an actual
Iterator
. No need to even think about indexes. TheIterator
has a remove method for these situations..