What analytics can you get from planck.js PostSolve?
The PostSolve event in planck.js provides crucial
physics simulation data immediately after collision impulses are
calculated and applied. By tapping into this event, developers can
gather precise analytics on collision forces, friction impulses, and
contact points between rigid bodies. This data is essential for
implementing gameplay mechanics like dynamic damage systems, sound
triggering based on impact severity, and game state analytics.
Understanding the PostSolve Event
In planck.js (a 2D JavaScript physics engine based on Box2D), the
physics step goes through several phases. The PostSolve
event fires after the solver has finished determining how to resolve a
collision. Unlike the PreSolve event, which lets you
disable contacts before they happen, PostSolve is strictly
for reading the exact physical outcomes of an interaction.
Key Data and Analytics Available
When you subscribe to the PostSolve event, the engine
passes a Contact object and a ContactImpulse
object to your listener. From these, you can extract several key
metrics:
- Normal Impulses: This is the most sought-after analytic. It represents the force applied perpendicular to the contact surface to prevent the bodies from interpenetrating. You can use the peak normal impulse to determine how “hard” an impact was.
- Tangent Impulses: This data represents the friction forces applied parallel to the contact surface. It tells you how much sliding resistance occurred during the collision.
- Contact Points and Normals: By accessing the
Contactobject’s manifold, you can pinpoint the exact spatial coordinates where the collision occurred and the direction of the impact vector.
Common Use Cases for PostSolve Data
- Impact Damage Systems: Instead of guessing if a hit was hard based on velocity alone, you can sum the normal impulses. If the total impulse exceeds a specific threshold, you can subtract health from an entity or break a destructible object.
- Dynamic Audio Triggering: You can map the magnitude of the normal impulse directly to the volume of a collision sound effect. A soft impulse triggers a quiet thud, while a massive impulse triggers a loud crash.
- Deformation and Visual Effects: Tangent impulses can be used to spawn spark particles along a surface for scraping effects, while normal impulses can determine the size of dust clouds or screenshake intensity.