How to Wake Up a Body in Planck.js?
Planck.js utilizes an automatic simulation feature called “sleep” to improve performance by excluding static or resting rigid bodies from physics calculations. However, there are scenarios where you need to manually intervene and force a sleeping body to become active again, such as when you programmatically alter its position or apply external logic. This article explains how to explicitly wake up a sleeping body in Planck.js using the built-in API, provides a practical code example, and outlines the common scenarios where this technique is required.
The setAwake() Method
The explicit and most direct way to wake up a sleeping body in
Planck.js is by calling the .setAwake() method on the body
instance. This method takes a boolean argument: passing
true immediately activates the body and puts it back into
the simulation loop, while passing false forces it to
sleep.
// Assuming 'body' is a reference to your planck.Body instance
body.setAwake(true);Practical Code Example
In a typical setup, bodies automatically fall asleep when they come to a rest. The following example demonstrates how to create a dynamic body, allow it to sleep, and then explicitly wake it up using user input or a timed event.
import planck from 'planck-js';
// 1. Initialize the physics world
const world = planck.World();
// 2. Create a dynamic body that is allowed to sleep
const body = world.createBody({
type: 'dynamic',
position: planck.Vec2(0, 10),
allowSleep: true // Ensures the body can sleep to save CPU
});
// Add a fixture (e.g., a box) so it has mass
body.createFixture(planck.Box(1, 1), 1.0);
// ... Let the simulation run until the body comes to a complete rest ...
// 3. Explicitly wake the body up later in your game loop or event handler
function triggerExplosionOrEvent() {
if (!body.isAwake()) {
body.setAwake(true);
// You can now safely apply forces or velocities
body.setLinearVelocity(planck.Vec2(0, -5));
}
}When is Explicit Wake Up Required?
While Planck.js automatically wakes up bodies during physical
collisions, it cannot detect changes made outside the physics engine’s
standard loop. You must explicitly call body.setAwake(true)
in the following situations:
- Manual Position Updates: If you manually change a
body’s position using
body.setPosition()orbody.setTransform(), neighboring sleeping bodies will not react unless you wake them up. - Direct Velocity or Force Modifications: Modifying a
body’s velocity via
body.setLinearVelocity()or applying forces programmatically does not always automatically wake up a deeply sleeping body. - Custom Game Logic: When triggering gameplay events like explosions, magnetic pulls, or wind forces that are calculated outside of standard fixture collisions, you must manually awake the affected bodies in the area.