2

I am creating and removing objects in an asteroid shooting game and only on some occasions it crashes and I get this error:

07-16 19:35:05.071: ERROR/AndroidRuntime(3553): FATAL EXCEPTION: Thread-11

07-16 19:35:05.071: ERROR/AndroidRuntime(3553): java.lang.IllegalStateException

07-16 19:35:05.071: ERROR/AndroidRuntime(3553): at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:69)

This is the code which tests for collision between shots and asteroids:

public void shotAstrCollision(){

    asterItr = asteroids.listIterator();

    while(asterItr.hasNext()){  
        aster = asterItr.next();
        shotItr = shots.listIterator();

        while(shotItr.hasNext()){   
            shot = shotItr.next();
            float shotToAst = (float) Math.sqrt((aster.x + astW/2 - shot.x)*(aster.x + astW/2 - shot.x) + (aster.y + astH/2 - shot.y)*(aster.y + astH/2 - shot.y));
            if (shotToAst < astW/2){
                //asteroid is shot
                aster.power -= shot.power;
                shotItr.remove();
                shotCount--;
                createExplosion(aster.x + astW/2, aster.y + astH/2);
                SoundManager.playSound(1, 1);
                if (aster.power <= 0) {
                    asterItr.remove();
                    astCount--; 
                }else{
                    aster.shotColor = ASTEROID_SHOT_PAINT_FRAMES;
                }
            }   
        }   
    }

}

Do you have any idea where to look for a possible cause of this error?

Lumis
  • 21,517
  • 8
  • 63
  • 67
  • You are calling `remove()` onto two different iterators: `shotItr` and, later, `asterItr`. Which is the line that throws the `IllegalStateException`? – Giulio Piancastelli Jul 16 '11 at 21:56

1 Answers1

9

After an asteroid is shot, you need to break out of the inner loop, where you're iterating over shots. Your code is finding that two different shots hit the same asteroid and trying to remove the same asteroid twice. This could also point to a problem with your collision detection, btw.

Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199
  • Well spotted, thank you! A fresh pair of eyes always helps! I should break out of the shot loop after the asteroid is removed. There must be too many asteroids in my head tonight... ;) – Lumis Jul 17 '11 at 00:05