开发者

illegalStateException when using ArrayList and iterator

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: ER开发者_如何学GoROR/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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜