How do dynamic bodies behave in planck.js?
In a planck.js simulation, a dynamic body is a fully simulated rigid body that reacts to external forces, gravity, and collisions with other objects. Unlike static or kinematic bodies, dynamic bodies possess mass and rotational inertia, allowing them to accelerate, bounce, slide, and rotate according to realistic Newtonian physics. This overview explores how these bodies interact within the physics engine, their key properties, and how developers can manipulate them for interactive applications.
Core Characteristics of Dynamic Bodies
A dynamic body is the most computationally intensive object type in planck.js because the engine must calculate its position and velocity at every simulation time step.
- Mass and Inertia: Dynamic bodies have non-zero mass and rotational inertia. These properties are automatically calculated based on the shapes (fixtures) attached to the body and their density.
- Forces and Impulses: You can apply forces (gradual changes in velocity) or impulses (instantaneous changes in velocity) directly to a dynamic body to move it or make it spin.
- Gravity: By default, dynamic bodies respond to the global world gravity vector. This causes them to fall unless supported by another object or joint.
Collision and Interaction
When a dynamic body collides with another object in the simulation, planck.js resolves the collision based on the material properties of both participating fixtures:
Friction and Restitution
Friction determines how easily two surfaces slide against each other, while restitution (bounciness) determines how much kinetic energy is retained after a collision. A dynamic body colliding with a high-restitution static floor will bounce upward, losing a portion of its energy based on the combined restitution coefficient.
Interaction Types
- Dynamic vs. Static: The dynamic body will bounce off or slide along the static body. The static body remains completely unmoved.
- Dynamic vs. Kinematic: The dynamic body reacts to the collision, but the kinematic body follows its own pre-defined velocity path unaffected by the impact.
- Dynamic vs. Dynamic: Both bodies exchange momentum based on their respective masses and velocities, resulting in realistic physical transfers where both objects bounce or deflect.
Sleeping and Performance Optimization
Because computing physics for dozens of dynamic bodies can be CPU-heavy, planck.js includes a “sleeping” mechanism. When a dynamic body comes to rest and stops interacting with moving objects, the engine puts it to sleep.
While asleep, the body is excluded from the physics update loop, saving valuable processing power. The engine automatically wakes the body up if another moving object collides with it, or if a developer applies a force or changes its velocity via code.