Find which bodies collide in Box2D using C ++

I have a base class for collision detection, but I cannot figure out how to see which bodies collide in order to trigger the corresponding event. Let's say I have a pong game and it has ballBody and topwallBody. As I understand it, if they collide or not. Here is a class that I use to give you an idea.

class MyListener : public b2ContactListener
{
    void BeginContact(b2Contact* contact)
    {
        b2Fixture* fixtureA = contact->GetFixtureA();
        b2Fixture* fixtureB = contact->GetFixtureB();
        b2Body* body1 = fixtureA->GetBody();
        b2Body* body2 = fixtureB->GetBody();
        cout << "started";
    }
    void EndContact(b2Contact* contact)
    {
        cout << "ended\n";
    }
};
MyListener listener;
world.SetContactListener(&listener);

It looks like I can get bodies in pointers, but I have no idea how to compare them with other bodies.

+3
source share
2 answers

When you create bodies, set something meaningful for userdata, but be consistent :) Good advice is to always have the same type and data type there, object identifier or actor link.

:

b2BodyDef bodyDef;

bodyDef.userData = &myActor;

, , b2Body - .

docs:

b2Fixture* fixtureA = myContact->GetFixtureA();

b2Body* bodyA = fixtureA->GetBody();

MyActor* actorA = (MyActor*)bodyA->GetUserData();

/ , ... actorA.explode().

, , . , , . , - .

+4

Skurmedel . , , , .

, , , . , , , .

        world.setContactListener(new ContactListener() {
        @Override
        public void beginContact(Contact contact) {

            Gdx.app.log("GameScreen", "Contact Made! Fixture A: " + contact.getFixtureA().getBody().getUserData().toString());
            Gdx.app.log("GameScreen", "Contact Made! Fixture B: " + contact.getFixtureB().getBody().getUserData().toString());
        }

toString, "Hear". userData , .

, , userData "" ..

GameScreen: Contact Made! Fixture A: Ground
GameScreen: Contact Made! Fixture B: Heart

, , , .

0

Source: https://habr.com/ru/post/1790561/


All Articles