Matter.js sleepThreshold Property Explained
The sleepThreshold property in Matter.js is a
performance-tuning setting that controls how quickly an idle physics
body enters a resting, or "sleeping," state. By automatically putting
motionless objects to sleep, the physics engine skips computationally
expensive collision checks and position calculations, substantially
boosting rendering and simulation performance in complex scenes.
How sleepThreshold
Works
In Matter.js, every physics body tracks its own motion level. When a dynamic body slows down and its movement falls below an internal motion limit, an idle counter begins incrementing.
The sleepThreshold defines the exact number of
consecutive simulation updates (ticks) this motion must remain below the
limit before the body officially falls asleep.
- Default Value:
60 - Real-time Equivalent: At a standard 60 frames per second (FPS), a threshold of 60 translates to approximately one full second of near-zero motion.
- Higher Values: Require the body to stay still longer before sleeping, reducing the chance of an object freezing prematurely.
- Lower Values: Make bodies sleep faster to maximize performance, but may cause objects to freeze mid-motion if they temporarily slow down.
Enabling Sleeping in Matter.js
For sleepThreshold to take effect, the engine's sleeping
module must be enabled globally, as it is turned off by default.
// Enable sleeping on the engine
const engine = Matter.Engine.create({
enableSleeping: true
});Configuring
sleepThreshold on a Body
You can define sleepThreshold on individual bodies
during creation or update it dynamically at runtime:
// Setting sleepThreshold at creation
const box = Matter.Bodies.rectangle(400, 200, 80, 80, {
sleepThreshold: 30 // Sleeps after ~0.5 seconds of inactivity at 60 FPS
});
Matter.Composite.add(engine.world, box);Waking Sleeping Bodies
Once a body is asleep (isSleeping: true), it remains
static until it is disturbed. Matter.js automatically wakes a sleeping
body when:
- Another active body collides with it.
- A force or impulse is manually applied using functions like
Matter.Body.applyForceorMatter.Body.setVelocity. - The body is manually awakened by setting
Matter.Sleeping.set(body, false).