How to Configure Sleep Threshold in Matter.js
This article explains how to configure the
sleepThreshold property in Matter.js to make resting bodies
enter a sleeping state more quickly. By default, Matter.js keeps bodies
awake for a set number of frames after motion stops, which consumes
computational resources. Lowering this threshold reduces the delay
before inactive bodies sleep, improving physics simulation performance
and frame rates in complex scenes.
Enabling the Sleeping Module
Before configuring individual body thresholds, sleeping must be explicitly enabled on the physics engine. By default, Matter.js leaves sleeping disabled.
const engine = Matter.Engine.create({
enableSleeping: true
});If enableSleeping is false, any
modifications to sleepThreshold will be ignored, and bodies
will remain awake continuously.
Understanding
sleepThreshold
The sleepThreshold property represents the number of
consecutive simulation updates (frames) a body's motion must remain
below a minimum energy threshold before it transitions into a sleeping
state (body.isSleeping = true).
- Default Value:
60(approximately 1 second of inactivity at 60 FPS). - Lower Values: The body requires fewer idle frames to sleep, allowing it to rest sooner.
- Higher Values: The body requires extended inactivity before sleeping, reducing the risk of premature freezing.
Configuring
sleepThreshold on Body Creation
To make a body sleep sooner, assign a lower integer to
sleepThreshold when instantiating the body via
Matter.Bodies.
const box = Matter.Bodies.rectangle(400, 200, 80, 80, {
sleepThreshold: 15 // Enters sleep mode after 15 idle frames (~0.25 seconds)
});
Matter.Composite.add(engine.world, box);Updating
sleepThreshold on Existing Bodies
You can adjust the value at runtime by setting the property directly on the target body instance:
// Target a specific body
box.sleepThreshold = 20;
// Apply to all bodies in a composite
const bodies = Matter.Composite.allBodies(engine.world);
bodies.forEach(body => {
body.sleepThreshold = 20;
});Best Practices for Tuning
- Avoid Setting Too Low: Setting
sleepThresholdbelow10–15can cause bodies to freeze mid-air or halt unnaturally while still undergoing slow, subtle movements. - Dynamic Waking: Sleeping bodies automatically wake when another awake body collides with them or when force/velocity is applied directly via code.
- Manual Sleep Control: If you need an object to
sleep immediately without waiting for any threshold counter, set
Matter.Sleeping.set(body, true).