Search code examples
box2dcollision-detection

How to make items collide with the floor but not with the player?


I want to have items (dynamic bodies) that collide with the floor (static body) due to gravity. But I don't want the player to collide with the items on the floor though I need to have a callback when the player overlaps an item (as if the item isSensor property was set to true).

Is it possible? I tried some configurations with the category bits and mask bits with no success.

I didn't have this problem before because items had a gravityScale set to 0 so they didn't fall on the floor. But now they need to respond to gravity.

Thanks.


Solution

  • You have to implement a class that extends b2ContactListener. You can choose to reject the collision in PreSolve() virtual function. In the b2Contact object that is passed to PreSolve(), you can get the 2 fixtures, from which you can derive what it actually collides with if you have stored a pointer to the user data before.

    Before you start the game engine, create new object of the subclass of b2ContactListener, then call method SetContactListener() of the game world object to set up the listener.

    Sample code