Search code examples
javalibgdxcollision-detectionbox2dcollision

how to perform an object delete when contact happens Box2D LibGDX


I'm trying to process a collision between a projectile and an enemy. When a projectile hits enemy it have to disappear, but instead a game is crushing in the moment of contact. I don't know how to fix that

public class CollisionProcessing implements ContactListener {
    World world;

    public static ArrayList<Body> deleteList = new ArrayList<>();

    public CollisionProcessing(World world) {
        super();
        this.world = world;
    }
    @Override
    public void beginContact(Contact contact) {}

    @Override
    public void endContact(Contact contact) {}

    @Override
    public void preSolve(Contact contact, Manifold manifold) {}

    @Override
    public void postSolve(Contact contact, ContactImpulse contactImpulse) {
        Fixture A = contact.getFixtureA();
        Fixture B = contact.getFixtureB();
        if (A == null || B == null) return;
        if (A.getUserData() == null || B.getUserData() == null) return;

        if (A.getUserData().equals(3)) {
            System.out.println("Bullet Body collision");
            deleteList.add(A.getBody());
        }
        if (B.getUserData().equals(3)) {
            System.out.println("Body Bullet collision");
            deleteList.add(B.getBody());
        }
    }
    public static ArrayList<Body> getDeleteList() {
        return deleteList;
    }
}

public void update() {
        deleteList = CollisionProcessing.getDeleteList();
        deleteList.forEach(obj -> {
            obj.setActive(false);
            world.destroyBody(obj);
        });
        world.step(1/60f, 6, 2);

        inputUpdate();
        cameraUpdate();
        enemies.forEach(enemy -> enemyUpdate(enemy));
        bullets.forEach(bullet -> bulletUpdate(bullet.getPoint().x, bullet.getPoint().y));

}

I have tried world.destroyBody() and body.destroyFicture() in an update method but it does not help. Also is tried to add new Body to an ArrayList in beginContact and it does not work too.


Solution

  • You cannot call any of the destroy' functions in any of the **Box2D** callbacks as they occur in during the World.step` update.

    Instead, in the postSolve add the body to a list and before you call World.step next time, iterate through that list and call destroyBody.

    Don't forget to clear the list after iterating through it.