How to Optimize Planck.js with Sleeping Bodies

Planck.js, a 2D JavaScript physics engine rewritten from Box2D, relies on sleeping bodies to drastically reduce CPU overhead by excluding stationary objects from physics calculations. This article explores how the “sleeping” mechanism works, why it is vital for maintaining a smooth frame rate in complex simulations, and how to configure it effectively in your code.


What is a “Sleeping” Body?

In a physics simulation, a rigid body can be in a few different states. When an object is moving, colliding, or being acted upon by forces, it is considered awake. However, when an object comes to a complete rest and remains undisturbed for a set period, Planck.js puts it to sleep.

Once a body is sleeping, the engine stops calculating its forces, velocities, and potential collisions. It remains in this low-overhead state until another awake object collides with it, or a developer manually wakes it up via code.

The Performance Impact of Sleep

Physics engines are notoriously CPU-intensive. Without sleeping bodies, a simulation must perform complex mathematical checks for every single object on every single frame—even if those objects are just sitting flat on the ground.

How to Enable and Manage Sleep in Planck.js

Sleeping is enabled by default in Planck.js, but you must ensure your world and body configurations support it to reap the performance benefits.

1. Enable Sleep on the World

When initializing your physics world, make sure allowSleep is set to true.

const world = pl.World({
  gravity: pl.Vec2(0, -10),
  allowSleep: true // Ensures the world permits bodies to sleep
});

2. Configure Individual Bodies

While the world allows sleeping, you can control the behavior on a per-body basis. By default, dynamic bodies will sleep automatically, but you can explicitly manage this or wake them up when applying custom logic.

const body = world.createBody({
  type: 'dynamic',
  position: pl.Vec2(0, 10),
  allowSleep: true // Can be set to false if an object must never sleep
});

// Manually waking a body up (e.g., if you manually move its position)
body.setAwake(true);

// Checking the status
if (body.isAsleep()) {
  // The body is currently sleeping and costing zero simulation time
}

Best Practices for Maximum Performance

To get the most out of Planck.js sleeping bodies, keep these tips in mind: