By default all bodies in Box2D world collide. But if we want a body to collide with only a select few bodies we use contact filtering. We will be specifying filters so we can control which object can collide with which.
In order to do this, we specify which objects can collide when we create b2FixtureDef during the b2Body creation phase. The object property we will be dealing with is b2FilterData property on the b2FixtureDef.

Category Bits and Mask Bits

The category bit is an unsigned integer (so only +ve numbers). The difference is that we use the bits of the unsigned integer to represent categories. With an integer being 16bit means we can specify 16 different categories. Once we have specified the category that the body belongs to, then we set another unsigned integer, called the category mask, to specify which categories the b2Body will collide with and won't collide with.
//... Some code
var fixDef = new b2FixtureDef;
fixDef.filter.categoryBits = 1;
fixDef.filter.maskBits = 4;
//... Some more code to follow
Collision Filtering

NOTE: The collision pairing must be mutual. That is if body A has a mask that specifies that it collides with body B, then body B must have a mask that specifies it collides with A, otherwise they will not collide. Or don't set maskBits for body B at all. It will behave as other bodies want it to behave.

(Play with Mouse)

In above example,
Here is the code snippet for the above condition:
		var bodyDef = new b2BodyDef;
		bodyDef.type = b2Body.b2_dynamicBody;
		bodyDef.userData = 'box';		
		var fixDef = new b2FixtureDef;
		fixDef.filter.categoryBits = 1;
		fixDef.filter.maskBits = 4;
		fixDef.density = 10.0;
		fixDef.friction = 0.5;
		fixDef.restitution = .5;		
		fixDef.shape = new b2PolygonShape;
		var box1 = world.CreateBody(bodyDef);
		bodyDef.userData = 'obj';
		fixDef.filter.categoryBits = 2;
		fixDef.filter.maskBits = 4;
		fixDef.restitution = .2; 
		fixDef.shape = new b2CircleShape(1);		  
        var wheel = world.CreateBody(bodyDef);
		//create a ground
        bodyDef.type = b2Body.b2_staticBody;
        bodyDef.position.Set(10, 14);
		fixDef.filter.categoryBits = 4;
		fixDef.filter.maskBits = 3;
		fixDef.shape = new b2PolygonShape;
        var ground = world.CreateBody(bodyDef);

By administrator at 01:01:12 AM 0 Comment(s)


There are no comments yet. Be the first one to add a comment!

Add a Comment

Please enter the email address.Invalid format. (Won't be Displayed)
Notify me of followup comments
Enter the displayed Code: captcha