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?

1
  • You are calling remove() onto two different iterators: shotItr and, later, asterItr. Which is the line that throws the IllegalStateException? Commented Jul 16, 2011 at 21:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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... ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.