I have a character in a 2D world that shots a projectile. I have a particular case where if there are 2+ objects overlapping, and I shoot them with my character, I get an array index out of bounds exception when I attempt to remove the projectile I shot from a local Array.
private Iterator<Enemy> enemyIter;
private Iterator<Bullets> bulletIter;
private Array<Enemy> enemyList = new Array<Enemy>();
private Array<Bullets> bulletsList = new Array<Bullets>();
bulletIter = bulletsList.iterator(); // If bullet touches enemy, remove enemy from enemyList
while(bulletIter.hasNext()) {
bullets = bulletIter.next();
enemyIter = enemyList.iterator();
while(enemyIter.hasNext()) {
enemy = enemyIter.next();
if (enemy.getBounds().overlaps(bullets.getBounds())) {
enemyIter.remove();
bulletIter.remove();
}
}
}
The issue happens on the “bulletIter.remove();” near the bottom.
Its an interesting problem because I know it only happens when I have two enemies that are overlapping each other, and I try to shoot them. I assume that the bullet overlaps multiple enemies, and therefore there is an exception when trying to remove the same bullet twice. I assumed that this wouldn’t happen for a single threaded application, so I’m very confused on how to solve this.
Any advice would be greatly appreciated!