Search code examples
c++collision-detectionbox2d

Find what bodies are colliding in Box2D using C++


I have a basic class for detecting collisions but I can't figure out how to see what bodies are colliding to trigger the appropriate event. Lets say I have a pong game and in it a ballBody and topwallBody. How would I figure out if these are colliding or not. Here is the class I'm using just 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 the bodies in the pointers but I have no idea how to compare them to other bodies.


Solution

  • When you create the bodies, set the userdata to something meaningful, but be consistent :) A good tip is to always have the same kind and type of data in there, an entity id or reference to an actor.

    Straight from the documentation:

    b2BodyDef bodyDef;
    
    bodyDef.userData = &myActor;
    

    So if you went this road you would get the actor from the b2Body and inform it of the collision, or do something else.

    Also from the docs:

    b2Fixture* fixtureA = myContact->GetFixtureA();
    
    b2Body* bodyA = fixtureA->GetBody();
    
    MyActor* actorA = (MyActor*)bodyA->GetUserData();
    

    In the code above you would have the actor/entity and could do whatever you would like... actorA.explode().

    Being consistent will likely save you from insanity. If one sticks all kinds of data in there it'll become really hard knowing what data is in what body. Plus you can't really handle the contacts in any generic way.