How to Create a Sleeping Body in Matter.js

In Matter.js, a sleeping body is a rigid body temporarily excluded from physics collision and motion updates to optimize performance. This guide covers how to enable the sleep module in the physics engine, initialize a body in a sleeping state, and manage transitions between sleeping and active states using the Matter.js API.

Step 1: Enable Sleeping on the Engine

By default, Matter.js disables the sleeping subsystem. Before any body can sleep, you must explicitly enable it on the Engine instance by setting enableSleeping to true.

const { Engine, Render, Runner, Bodies, Composite, Sleeping } = Matter;

const engine = Engine.create({
  enableSleeping: true
});

If enableSleeping remains false, any sleeping configurations applied to individual bodies will be ignored.

Step 2: Initialize a Body in a Sleeping State

To create a body that is asleep immediately upon creation, pass { isSleeping: true } within the body options object.

const box = Bodies.rectangle(400, 200, 80, 80, {
  isSleeping: true
});

Composite.add(engine.world, box);

When the simulation begins, this body will not move, fall due to gravity, or consume CPU cycles for movement calculations until an awake body collides with it or it is awakened manually.

Step 3: Programmatically Set Sleep State

You can put existing bodies to sleep or wake them up using the Matter.Sleeping module.

Waking a Body

// Wake up a specific body
Sleeping.set(box, false);

Putting a Body to Sleep

// Force a specific body to sleep immediately
Sleeping.set(box, true);

Configuring Sleep Thresholds

Bodies automatically fall asleep after remaining below a motion threshold for a specified number of frames. You can fine-tune this behavior globally or per body using the sleepThreshold property (default is 60 updates).

const sensitiveBox = Bodies.rectangle(400, 200, 80, 80, {
  sleepThreshold: 15 // Falls asleep much faster once motion drops
});

Higher thresholds require a body to be completely still for longer before sleeping, while lower thresholds make bodies sleep rapidly.