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).

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

  1. Avoid Setting Too Low: Setting sleepThreshold below 1015 can cause bodies to freeze mid-air or halt unnaturally while still undergoing slow, subtle movements.
  2. Dynamic Waking: Sleeping bodies automatically wake when another awake body collides with them or when force/velocity is applied directly via code.
  3. Manual Sleep Control: If you need an object to sleep immediately without waiting for any threshold counter, set Matter.Sleeping.set(body, true).