Buffering ContactPoints

From Box2D Wiki

Because Box2D 2.0 introduced the ContactListener, it has become important to write a method that stores the contact points into a single buffer for objects that require data about what it is currently colliding with. This article provides a method that uses std::map to buffer ContactPoints from the contact listener into a Game Object.

A GameObject consists of a Box2D body and a map of an integer and a ContactPoint. The integer is used as the key, and will later be equal to ContactPoint.id.key. Please see http://cppreference.com/ for more information about std::map.

class GameObject {
public:
    GameObject(float width, float height);
 
    b2Body *body;
    std::map<int, b2ContactPoint *> contact_list;
};


The constructor creates a body and sets the UserData to itself.

GameObject::GameObject(float width, float height) {
    b2PolygonDef shapedef;
    shapedef.SetAsBox(width/2.0, height/2.0);
    shapedef.density = 0.5;
    shapedef.isSensor = false;
    shapedef.friction = 0.5;
    shapedef.restitution =  0.05;
 
    b2BodyDef bodydef;
    bodydef.position.Set(0.0f, 0.0f);
 
    b2Body *body = world->CreateBody(&bodydef);
    body->CreateShape(&shapedef);
    body->SetMassFromShapes();
 
    body->SetUserData( (void *)this );
}

The UserData will be used later to get the contact list from the body's corresponding GameObject. A class that implements b2ContactListener is created, implementing Add and Remove.

class CustomListener : public b2ContactListener {
public:
    void Add(b2ContactPoint *point);
    void Remove(b2ContactPoint *point);
};

Now to implement Add. Each contact point has an id, which has a unique integer called "key". This is what we will use to make sure that the contact list only has one copy of any one contact point. Because we set the user data equal to the body's GameObject, we can retrieve it by calling GetUserData, and casting it to the GameObject type. This is done for both shapes in the game object. A new ContactPoint must be created for both GameObjects, because it is not guaranteed that Box2D will keep the pointer alive, and they must be unique to both objects so that deleting one won't delete the other.

void CustomListener::Add(b2ContactPoint *point)
{
   GameObject *gameobject1 = static_cast<GameObject *> ( point->shape1->GetBody()->GetUserData() );
   GameObject *gameobject2 = static_cast<GameObject *> ( point->shape2->GetBody()->GetUserData() );
 
   gameobject1->contact_list[point->id.key] = new b2ContactPoint(*point); // copy constructor
   gameobject2->contact_list[point->id.key] = new b2ContactPoint(*point); // copy constructor again
}

Note: There is a problem with this setup if you choose to get the contact normal. Add is not called for each body that is touching, so the normal in b2ContactPoint is relative to shape1. This means that shape2 will get a vector that is the opposite of what it should be. The way I do it is that I flip the normal for gameobject2 inside of the Add function, by doing something like:

b2ContactPoint *point2 = new b2ContactPoint(*point);
point2->normal.x *= -1;
point2->normal.y *= -1;

Lastly, the function Remove must be implemented. Because we made the key equal to the contact id, it will be easy to find the contact point that is being removed, and delete it from the std::map. This is done using the find method of the map, which will return an iterator to the contact point (or just past the end of the contact list if a contact point could not be found).

void CustomListener::Remove(const b2ContactPoint *point)
{
	GameObject *p1 = static_cast<GameObject *> ( point->shape1->GetBody()->GetUserData() );
	GameObject *p2 = static_cast<GameObject *> ( point->shape2->GetBody()->GetUserData() );
 
	std::map<int, b2ContactPoint *>::iterator iter;
 
	iter = p1->contact_list.find(point->id.key);
	if(iter != p1->contact_list.end() ) {
		delete (*iter).second; //necessary since we called new on it
		p1->contact_list.erase(iter);
	}
 
	iter = p2->contact_list.find(point->id.key);
	if(iter != p2->contact_list.end() ) {
		delete (*iter).second;
		p2->contact_list.erase(iter);
	}
}
/*
edit by jonathan (raz) xx.darksilence.xx[at]gmail.com
 
note: did you mean "contact_list" ?? you referenced it as "contacts"
note: you declared a map iterator as "b2Vec2 *" but declared the actual map as "b2ContactPoint *"
 
you can't iterate through a map as "b2Vec2 *" when it's actually a "b2ContactPoint *"
 
seriously though, great work on the solution --
i'm putting this here as a note because i don't know if i'm wrong or right
 
feel free to comment back, thanks for your contribution
 
edit by ionstream:
yeah you're right, I started making this based off of my code (which was a bit different), but I got tired and forgot to change the last part to match the first, sorry about that! there still might be errors though, i'll look them over tomorrow
 
*/

A GameObject can now access its contact list by accessing its map, which is done like so:

std::map<int, b2ContactPoint *>::iterator iter = gameobject->contact_list.begin();
while (iter != gameobject->contact_list.end())
{
   b2ContactPoint *point = (*iter).second;
   // do something with the point...
 
   // get next point
   ++iter;
}

May someone find this useful!

Image:Icon-tutorials.png‎ Tutorials

General

AS3

TOOLBOX
LANGUAGES