Search code examples
box2dcocos2d-xcollision

How to check which objects collide with b2Contact?


I want to check colission between two bodies in my game. I have two different bodies, a rayman (character) and a key. I want to check the colission between these two. I have made a class that extends b2ContactListener, I have overridden the BeginContact method, but I don't know where to go from here:

void MyContactListener::BeginContact(b2Contact *contact)
{
    if(contact->GetFixtureA()->GetBody()->GetUserData())
    {
        ContactData C= { contact->GetFixtureA(), contact->GetFixtureB() };
        cocos2d::CCLog("asdf");
    }
}

I can get the the userdata, but how do I know if the userdata is rayman or the key or an entirely different object?


Solution

  • The idea is, you will store the necessary information in the user data. A typical case might be:

    struct bodyUserData {
        int bodyType;
        ... whatever other stuff you need  ...
    };
    

    When you create the body, you would create a user data to attach info to it:

    b2Body* body = world->CreateBody(...);
    
    bodyUserData* bud = new bodyUserData;
    bud->bodyType = BT_RAYMAN; // some integer to signify what the body is
    
    body->SetUserData( bud );
    

    In the contact listener, you can check what type of thing the body is:

    b2Body* body = contact->GetFixtureA()->GetBody();
    
    bodyUserData* bud = (bodyUserData*)body->GetUserData();
    if ( bud ) {
        if ( bud->bodyType == BT_RAYMAN )
            ... body is rayman ...
        else if ( bud->bodyType == BT_KEY )
            ... body is a key ...
    }
    

    Remember to delete the user data before destroying the body :)