Box2D for Collision Detection Only

Hi,

I am using Box2D for collision detection only. My code is similar to that in Ray Wenderlich's tutorial here.

I am encountering a problem with this method. Since the code bypasses the Box2D simulation, there is no collision response. Therefore, sprites can overlap. I am aware that Box2D collision APIs provide a unit normal vector to help resolve collisions. However, this vector conveys direction but not magnitude. Therefore, I cannot determine how far I should move overlapping sprites. Does anyone know how to use the Box2D collision APIs to determine how to manually resolve an overlap?
slhertz wrote:
I am using Box2D for collision detection only.

Hmm... but the rest of your post says otherwise, that you are in fact wanting to use it for collision response as well. Box2D does a pretty good job of collision response so I would think the recommended practice is to let it do that.

To answer your question though, no, there is nothing in the API that lets you conveniently know a distance to move something to prevent overlap. This is because the engine itself does not simply move things according to how much they are overlapping, it calculates the impulses necessary to bump them enough so that they stop overlapping. This depends on a whole bunch of factors such as the linear and angular velocity of the two colliding things, their restitution, friction, relative masses and centers of mass, and of course the fact that they may be in contact with more than one other body, and if so all of the contacts must be solved for together to keep piles stable etc. Depending on how the things are overlapping, the collision may actually need to be resolved by a rotation instead of a translation. Depending on the shape of the things colliding, there may even be more than one impulse necessary. This whole process is done iteratively, typically many times per time step. There is a lot going on in there, that you would be hard pressed to replicate by simply moving along a normal.

Obviously Box2D has this information to work with though, so your question is not unreasonable. For polygons, maybe you could make some use of these internal functions in b2CollidePolygon.cpp:
b2FindMaxSeparation
b2FindIncidentEdge
I appreciate the thorough response. I'll take a look at the the functions you've cited.

If I use Box2D for its physics, then I won't be able to use any of the wonderful position-modifying actions included with cocos2d 🙁

Original thread: https://box2d.org/forum/viewtopic.php?t=9283