B2ContactFilter

From Box2D Wiki

b2ContactFilter
Box2D/Dynamics
Visibility Public
Manual reference [1]
API reference [2]
Source reference H.png Cpp.png

The world's contact filter allows stronger customization of filtering of shapes-vs-shapes and shapes-vs-rays than just setting b2FilterData. It can be used like a listener: you must subclass b2ContactFilter, and then attach it with b2World::SetContactFilter.

Every time two shapes come near colliding, the virtual method ShouldCollide is called. This should return true if the given shapes should be allowed to collide. The returned value is used until the shapes are sufficiently far away (and the pair destroyed). b2ContactFilter is not appropriate for uses where details of the collision need to be known to determine the result.

The default implementation is:

bool b2ContactFilter::ShouldCollide(b2Shape* shape1, b2Shape* shape2)
{
	const b2FilterData& filter1 = shape1->GetFilterData();
	const b2FilterData& filter2 = shape2->GetFilterData();
 
	if (filter1.groupIndex == filter2.groupIndex && filter1.groupIndex != 0)
	{
		return filter1.groupIndex > 0;
	}
 
	bool collide = (filter1.maskBits & filter2.categoryBits) != 0 && (filter1.categoryBits & filter2.maskBits) != 0;
	return collide;
}

Raycasting

Customization of filtering of rays used in raycasting is also possible. In this case, the function RayCollide should be implemented, which takes the userData value originally passed to Raycast and a pointer to the shape in question.

The default implementation is to fall back to ShouldCollide:

bool b2ContactFilter::RayCollide(void* userData, b2Shape* shape)
{
  //By default, cast userData as a shape, and then collide if the shapes would collide
  if(!userData)
    return true;
  return ShouldCollide((b2Shape*)userData,shape);
}

However, a popular alternative is to allow userData to be a pointer to a b2FilterData, and filter that as usual:

bool b2ContactFilter::RayCollide(void* userData, b2Shape* shape)
{
	if(!userData)
		return true;
	const b2FilterData& filter1 = *static_cast<b2FilterData*>(userData);
	const b2FilterData& filter2 = shape->GetFilterData();
 
	if (filter1.groupIndex == filter2.groupIndex && filter1.groupIndex != 0)
	{
		return filter1.groupIndex > 0;
	}
 
	bool collide = (filter1.maskBits & filter2.categoryBits) != 0 && (filter1.categoryBits & filter2.maskBits) != 0;
	return collide;
}


TOOLBOX
LANGUAGES