Search code examples
libgdxdestroybullet

Libgdx destroying multiple bodies


So basically i get an error when trying to destroy bodies that are not in screen bounds. Also my one type bodies start to act strange when other type bodies are destroyed ( example bullets starts to move backwards) here are the code samples :

Maingame loop class:

Array<Body> bodies = new Array<Body>(world.getBodyCount());
    world.getBodies(bodies);
    for (Body body : bodies) {
        check = 0;
        if (BodyUtils.bodyIsEnemy(body)){
            update(body);
            check = 1;
        }
        if (BodyUtils.bodyIsBullet(body) && check == 0){
            update1(body);
            check = 0;
        }
    }

private void update(Body body) {
    if (!BodyUtils.bodyInBounds(body)) {
        if (BodyUtils.bodyIsEnemy(body) && !player.isHit()) {
            createEnemy();
        }
        world.destroyBody(body);
    }
}

private void update1(Body body) {
    if (!BodyUtils.bulletInBounds(body))
        world.destroyBody(body);
}

Other class:

public static boolean bodyInBounds(Body body) {
        UserData userData = (UserData) body.getUserData();
        switch (userData.getUserDataType()) {
        case ENEMY:
            return body.getPosition().x + userData.getWidth() / 2 > 0;
        }
        return true;
    }

    public static boolean bulletInBounds(Body body) {
        UserData userData = (UserData) body.getUserData();
        switch (userData.getUserDataType()) {
        case BULLET:
            return body.getPosition().x + userData.getWidth() < 20;
        }
        return true;
    }

Solution

  • Fixed it , createEnemy() method placed after world.destroyBody(body) method.