0
votes

Kindly suggest some explanation or code regarding how can i detect collision between a specific part of one body with another body in box2d with libgdx.I am able to detect simple collision between two bodies using Contact Listener as mentioned hereBut I also want to check which part of bodies are ovelapping.

Thanks,

1

1 Answers

1
votes

The ContactListener provides you with Contact as a callback parameter. Those contacts will tell you which Fixtures did collide via contact.getFixtureA() and contact.getFixtureB().

What people usually do to find out which part of their bodies collided, is to build them with several Fixtures via body.createFixture(...).

You can set user data on Fixture as well as on Body with fixture.setUserData() and body.setUserData(). You could either save your fixture somewhere else and compare via contact.getFixtureA() == xxx.savedFixture.

That might be in your entity for example like the following:

public class Player {
    public Fixture arm;

    // create the player body and store the arm fixture
    body.setUserData(this);
    arm = body.createFixture(...);
}

Then later you can do this in your contact listener:

public void beginContact(Contact contact) {
    if (contact.getFixtureA().getBody().getUserData().getClass().equals(Player.class)) {
        if (contact.getFixtureA() == ((Player)contact.getFixtureA().getBody().getUserData()).arm == contact.getFixtureA()) {
            // the arm collided with something
        }
    }
}

Or you might just add some user data like fixture.setUserData("arm") which you can then easily check. In your contact callback handler.