Detect whether a specific part of body collided with another body in box2d

只谈情不闲聊 提交于 2019-12-12 04:37:38

问题


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:


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.



来源:https://stackoverflow.com/questions/23005161/detect-whether-a-specific-part-of-body-collided-with-another-body-in-box2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!