How to Force a Body to Sleep in Matter.js
Forcing a physics body to sleep immediately in Matter.js allows you
to freeze its simulation and save computational resources without
removing it from the world. To achieve this, you must enable the
sleeping feature on the Matter.js engine and call the dedicated
Matter.Sleeping.set() method on the target body. This guide
explains how to enable sleep functionality, execute the command, and
ensure the body stops moving right away.
1. Enable Sleeping on the Engine
By default, body sleeping is disabled in Matter.js. You must enable it when creating your physics engine or update the property on an existing instance:
// When creating the engine
const engine = Matter.Engine.create({
enableSleeping: true
});
// Or enabling it on an existing engine instance
engine.enableSleeping = true;If enableSleeping is set to false, any
attempts to set a body's sleep state manually will be ignored by the
engine.
2. Use
Matter.Sleeping.set
To force a specific body into an immediate sleep state, use the
Matter.Sleeping.set method and pass true as
the second argument:
Matter.Sleeping.set(body, true);This immediately sets body.isSleeping to
true, halts automatic velocity calculations, and excludes
the body from broadphase collision checks until it is disturbed or
manually awakened.
3. Complete Code Example
const { Engine, Render, Runner, Bodies, Composite, Sleeping } = Matter;
// Create engine with sleeping enabled
const engine = Engine.create({
enableSleeping: true
});
const world = engine.world;
// Create a falling box
const box = Bodies.rectangle(400, 200, 80, 80);
Composite.add(world, box);
// Force the box to sleep immediately
Sleeping.set(box, true);4. Zeroing Velocities (Optional Safeguard)
In most cases, Sleeping.set(body, true) halts the body
completely. However, if forces or impulses were applied in the same
tick, resetting linear and angular velocities ensures there is no
residual momentum when the body eventually wakes up:
Matter.Body.setVelocity(body, { x: 0, y: 0 });
Matter.Body.setAngularVelocity(body, 0);
Matter.Sleeping.set(body, true);5. Waking the Body
To wake the body up programmatically at a later time, pass
false to the same method:
Matter.Sleeping.set(body, false);A sleeping body will also wake up automatically if it collides with an active, awake body.