1
votes

I am working on a game in box2d. I have the following code:

    for (int contact_num = 0; contact_num<contact_count; ++contact_num)
{
    if (contact->IsTouching())
    {
        // get the colliding bodies
        b2Body* bodyA = contact->GetFixtureA()->GetBody();
        b2Body* bodyB = contact->GetFixtureB()->GetBody();

        // check if one of the colliding objects is a censor
        bool sensorA = contact->GetFixtureA()->IsSensor();
        bool sensorB = contact->GetFixtureB()->IsSensor();

        // do stuff, mainly handling variables

        }
    }
    // Get next contact point
    contact = contact->GetNext();
}

All of this is being called in the update function of my main class (which also contains most of the games variables). The problem is that I want the code to only be called when the two objects first collide, because otherwise something like score++ will end up skyrocketing in value as it gets updated for the collisions duration. I am aware of a "contact listener" class in box2d with the function "begin contact", but there is no good documentation that could help a beginer learn how to implement it. For example, if I add a contact listener to my main class, how do I get it to handle my score, for example, if the contact listener doesn't have access to those variables? Or where do I call "begin contact" in the first place? Sorry if these are obvious questions, but i was hoping someone could clarify these. Thank you in advance.

1

1 Answers

2
votes

Here's a couple suggestions which hopefully will answer your question:

  1. Take a look at Box2D C++ tutorials - Collision callbacks. Personally, I think it's a great tutorial on using the b2ContactListener class.
  2. Just make your class which contains the score information inherit from b2ContactListener. That way your BeginContact method will have direct access to the score data. Presumably that'll be your "main" class. Be sure to also notify your b2World instance to use this by calling your world instance's SetContactListener method with a pointer to the score containing instance (that you'd subclassed from b2ContactListener).

If you still need more help with this, please add a comment to that effect or update your question to reflect what remains unclear.