I am writing a "Gauntlet" style game. So far I have managed to successfully detect collisions between my player object and my ghost enemy objects, and when they collide they drain the player's energy.
The Ghosts are stored in an ArrayList. I now have bullets which the player can fire, these are instantiated from the Player class and added to another ArrayList called bullets.
I typically have around 50 ghosts on the screen dotted around the map.
ArrayList<Ghost> ghosts = new ArrayList<Ghost>();
ArrayList<Bullet> bullets = new ArrayList<Bullet>();
The ghosts and bullets are added to these lists when spawned/fired
I have tried to implement a method as per below, to try and determine whether a ghost's bounding rect and a bullet's bounding rect overlap, as follows:
/**
* Check if a ghost has been hit by a bullet
*/
public void checkGhostsHit() {
Iterator<Ghost> iterEn = ghosts.iterator();
while ( iterEn.hasNext() ){
Ghost g = iterEn.next();
//initialise the bullet iterator each time here
Iterator<Bullet> iterBul = Player.bullets.iterator();
while ( iterBul.hasNext() ) {
Bullet b = iterBul.next();
if ( b.getBoundingRect().overlaps( g.getBoundingRect() ) ) {
Gdx.app.log("Enemy", " Hit");
iterBul.remove();
iterEn.remove();
}
}
}
}
This method is being called from my main render loop but I cannot get it working for love or money. I have tried various forms of the above method, including 'For' loops etc.
Am I performing the check in the correct place? Should the Bullet class instance iteself be checking for a collision, or is the above approach the correct idea.
As you can tell I'm a noob to this and I am still struggling with working out which activities should be undertaken by particular game Classes.
ConcurrentModificationException
when the bullets finally start hitting. Avoid using iterators if you're going to add or remove from the list while iterating. \$\endgroup\$