How to Wake Up a Sleeping Body in Matter.js

In Matter.js, physics bodies enter a sleeping state to save CPU performance when they come to rest, ceasing collision checks and movement updates until disturbed. Waking up a sleeping body is necessary when you need it to react instantly to user input, script triggers, or environmental changes without waiting for an external collision. This guide demonstrates how to wake a sleeping body using the Matter.Sleeping module and how to prevent unwanted sleep states in your simulation.

The Primary Method: Matter.Sleeping.set

The direct and standard way to wake up a sleeping body is using the Sleeping.set method provided by the Matter.js engine. Pass the target body and false as the state:

// Import or alias the Sleeping module
const Sleeping = Matter.Sleeping;

// Wake up the target body
Sleeping.set(myBody, false);

Setting the state to false immediately switches the body's isSleeping property to false, resets its internal sleep counter, and re-engages it in the physics engine's active collision and update cycles.

Waking Bodies by Applying Forces or Velocities

Modifying a body's velocity or applying a force can also trigger a wake-up, depending on your engine setup. However, directly setting position or angle does not automatically wake a body.

If you want a body to move after being manipulated manually, always call Sleeping.set(body, false) alongside your modifications:

const Body = Matter.Body;
const Sleeping = Matter.Sleeping;

// Wake the body before or immediately after applying velocity
Sleeping.set(myBody, false);
Body.setVelocity(myBody, { x: 5, y: -10 });

Waking All Bodies Simultaneously

If your scene requires multiple sleeping bodies to activate at once (such as an explosion or sudden gravity shift), iterate through your engine's world composite:

const Composite = Matter.Composite;
const Sleeping = Matter.Sleeping;

const allBodies = Composite.allBodies(engine.world);

allBodies.forEach(body => {
    if (body.isSleeping) {
        Sleeping.set(body, false);
    }
});

Preventing a Body from Falling Asleep

If a specific body must remain active indefinitely, you can adjust its sleepThreshold. Setting this property to a negative value or Infinity prevents the body from ever entering the sleep state:

// Prevent the body from ever sleeping
myBody.sleepThreshold = -1;

Alternatively, you can disable the sleeping system entirely across the entire physics simulation by setting enableSleeping: false in your Engine.create() configuration.