Today, we will once again be returning to the topic of collisions to answer a request which was, “how to determine the strength involved in a collision”. By gaining access to this information, we can then decide when to implement sound effects, damage modeling, score, etc.
Currently, we have been using the b2ContactListener for detection of when a collision occurs by overwriting the BeginContact function and accessing the b2Contact parameter. However, you will notice that the b2Contact does not offers us anything for determining the forces involved in a collision.
The secret is that we need to make use of another function of the b2ContactListener, the PostResolve function, which is called after collision detection and resolution has occurred. By overwriting this, not only do we get access to a b2Contact parameter, but we can also gain access to a b2ContactImpulse parameter.
The b2ContactImpulse has two fields of interest. The normalImpulses and tangentImpulses, both of type Vector. A quick look in the Box2D manual reveals their purpose:
- normal impulse
The normal force is the force applied at a contact point to prevent the shapes from penetrating. For convenience, Box2D works with impulses. The normal impulse is just the normal force multiplied by the time step. - tangent impulse
The tangent force is generated at a contact point to simulate friction. For convenience, this is stored as an impulse.
So it would seem normal impulse is what we are after. My understanding is the force to prevent shapes overlapping is going to be equal to the force causing it to overlap in the first place.
Thus for each contact, we will receive a Vector of normalImpulses. However, from my tests, it seems only the first value is of any use, with the second value seemingly to always be 0 (in saying so, there is probably a case where this won’t be true). We can then use this value to determine the magnitude of the force and use this however we please. In my asteroids demo, I simply check to see if this value is above a threshold, and if it is, I mark it for exploding.
原文地址:http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-6-collision-strength/