Search code examples
javaandroidlibgdx

libGDX's Collision is not working properly in my update method


I have a project in android studio for libGDX. I used this collision system in my player class and it worked! But when I check in my Bullet class it doesn't work and gives me an error!

('em' is an entity manager btw) (em.entities is an Array which is libgdx's version of an ArrayList)

for (Entity e : em.entities) {
    if (e instanceof Enemy) {
        if (getBounds().contains(e.getBounds())) {
            System.out.println("Collided!");
        }
    }
}

This is the error:

Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: #iterator() cannot be used nested. at com.badlogic.gdx.utils.Array$ArrayIterator.hasNext(Array.java:550) at com.thechief.game.entities.EntityManager.update(EntityManager.java:35) at com.thechief.game.screen.GameScreen.update(GameScreen.java:29) at com.thechief.game.Main.render(Main.java:50) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:225) at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)


Solution

  • Don't use the iterator, as that is not allowed for nested loops. Just use a traditional for loop instead of an iterator.

    for(int i=0;i<em.entities.size;i++){
        Entity e=em.engities.get(i);
        if (e instanceof Enemy) {
             if (getBounds().contains(e.getBounds())) {
                    System.out.println("Collided!");
             }
        }
    }