OK, so I'm developing a small game about bouncing a ball around to hit enemies and power-ups. I got the ball moving and bouncing on walls, enemies and the player character, but I just can't make power-ups disappear upon being touched by the ball.
I've read several threads asking a similar question, and have tried all the solutions that were proposed: setting the power-up object to null, removing it from the ArrayList it's stored in with remove(), storing its location in the ArrayList to remove it later using this location... I've even tried to set up a system of ids to remove it from the ArrayList by using its unique ID. But the result is always the same: when the ball hits the power-up, the game freezes and it throws a ConcurrentModificationException.
(The method tick() in the class PowerUp below is called 60 times per second for each power-up in the ArrayList powerups; getBounds() returns a Rectangle with the entity's coordinates and dimensions, it works perfectly).
public class Game {
public static ArrayList<PowerUp> powerups = new ArrayList<PowerUp>();
}
public class PowerUp {
public void tick(){
if(this.getBounds().intersects(Game.gameBall.getBounds())){
this.activate();
}
}
private void activate(){
//do whatever
//delete this from the game
Game.powerups.remove(this);//this is what I tried first
}
}
So, how do I delete the power-up without getting that damnable exception?