Search code examples
c++objective-ccocos2d-iphonebox2dcollision-detection

how to prevent tunneling on sensor objects in Box2D


I'm making an ipad game using cocos2d and box2d.

Among other elements, there's a fast-moving player object and a bunch of static line objects. I want the lines to detect when the player crosses them but not to act like a wall to the player object or any other moving objects in the game. So I've got the lines set to be sensors.

However, the nifty anti-tunneling code that Box2D has for fast-moving object collision detection doesn't seem to apply to bodies that are set as sensors. So now my player object passes right through the lines and only gets detected maybe one time in five.

How can I get box2d to detect the sprite crossing the line every time, no matter how fast it's going?

Edit: I found this post on the box2D forums where someone had a similar issue and found a possible solution. However I don't follow how to implement the solution. Maybe it'll help someone else, or maybe someone can explain what this person did more clearly. Here's what they said:


Solution

  • OK I got it working. Someone responded in the Box2D forums with a solution, which is to use a ray cast instead of relying on the built-in collision detection. I was able to find instructions on how to do this in this excellent tutorial on RayWenderlich.com

    For my purposes, I simply calculated the sprite's velocity from the last frame, then performed a ray cast to see if it crossed any lines. The callback gives the x,y coordinate of where it crossed.