Home > iPhone Development > Cocos2d – Contact Filter in Box2d

Cocos2d – Contact Filter in Box2d

In Box2d, we can easily define what kind of shapes can collide with each other. The shapes that do not collide with each other will overlap. Generally, there are three ways to achieve this:

Method 1 – Define collision groups with group index. The shapes which are in the same group and have positive (negative) index will always (never) collide with each other. This is the simplest way to define what kind of shapes can collide with each other, but it has limitations. Collisions between the shapes which are in the different groups need to be filtered in other ways.

Example: In our previous example, if we want the ball doesn’t collide with the ground, we can just add the following codes in the initialization:

groundShapeDef.filter.groupIndex = -1;

ballShapeDef.filter.groupIndex = -1;

Method 2 – Define category and mask bits. This method is a little more complex than Method 1, but it can filter the collision not only between the shapes in the same category, but also between the shapes in different categories.

Example:

groundShapeDef.filter.categoryBits = 0×0002;
groundShapeDef.filter.maskBits = 0×0008;

ballShapeDef.filter.categoryBits = 0×0008;
ballShapeDef.filter.maskBits = 0×002;

With the codes above, the ball will collide with the ground, but the balls will not collide with each other.

Method 3 – Implementing our own contact filtering function. We need to derive from class b2ContactFilter and implement the method ShouldCollide. From the documentation, you can see the default behavior of method ShouldCollide. It can be seen that group filtering (Method 1) has higher precedence than category filtering (Method 2).

Categories: iPhone Development
  1. No comments yet.
  1. No trackbacks yet.