How to Enable or Disable Sleeping in Matter.js

This guide explains how to globally enable or disable the sleeping mechanism in a Matter.js physics engine. By managing sleeping at the engine level, you can significantly improve simulation performance by pausing physics calculations on stationary bodies, or disable it to ensure all bodies remain continuously active and responsive to subtle forces.

In Matter.js, "sleeping" allows rigid bodies that have come to a complete rest to stop updating until another active body collides with them or an external force is applied. By default, the sleeping feature is disabled (false) when you create a new engine.

Setting Sleeping During Engine Initialization

The most common way to configure sleeping globally is through the configuration object passed to Engine.create():

const { Engine } = Matter;

// Create an engine with sleeping globally enabled
const engine = Engine.create({
    enableSleeping: true
});

To explicitly ensure sleeping is turned off, set enableSleeping to false:

// Create an engine with sleeping globally disabled
const engine = Engine.create({
    enableSleeping: false
});

Modifying Sleeping on an Existing Engine

If your engine is already running, you can toggle sleeping dynamically by directly modifying the enableSleeping property on the engine instance:

// Globally enable sleeping
engine.enableSleeping = true;

// Globally disable sleeping
engine.enableSleeping = false;

Important Considerations

When enableSleeping is set to true, the engine automatically monitors the motion of bodies. If a body's speed drops below the sleep threshold for a sustained period, Matter.js changes its state to body.isSleeping = true.

If your simulation involves small, subtle forces (such as low-gravity environments, gentle wind, or continuous micro-vibrations), sleeping can sometimes cause bodies to freeze prematurely. In these scenarios, keep enableSleeping: false to maintain continuous simulation accuracy across all objects. Conversely, for large scenes with many static stacks of bodies, enabling sleeping provides a substantial frame rate boost.