How to Use the sleepStart Event in Matter.js

The sleepStart event in Matter.js allows developers to detect the exact moment a physics body ceases movement and enters a sleeping state to save computation. By default, Matter.js keeps bodies active, but enabling the sleeping module automatically deactivates idle objects until an external force acts on them. This guide explains how to configure engine-level sleeping, attach a listener to the sleepStart event, and leverage the event to optimize physics simulations or update object aesthetics.

Enabling Sleeping on the Engine

Before the sleepStart event can trigger, you must explicitly enable sleeping on your Matter.js engine instance. When disabled, bodies continuously calculate velocities and collisions even if they are virtually motionless.

Set enableSleeping: true upon engine creation, or set the property on an existing engine instance:

// During engine initialization
const engine = Matter.Engine.create({
    enableSleeping: true
});

// Or dynamically on an existing engine
engine.enableSleeping = true;

Attaching the sleepStart Event Listener

Matter.js dispatches the sleepStart event directly through its Events module. The event triggers individually on the specific Body that goes to sleep.

Use Matter.Events.on() to register a listener on the target body:

const { Engine, Render, Runner, Bodies, Composite, Events } = Matter;

const engine = Engine.create({ enableSleeping: true });
const world = engine.world;

// Create a physical body
const box = Bodies.rectangle(400, 200, 60, 60, {
    render: { fillStyle: '#3498db' }
});

// Listen for the sleepStart event on the body
Events.on(box, 'sleepStart', function(event) {
    console.log('Body is now sleeping:', event.source);
    
    // Example: visually dim the body to indicate it is dormant
    event.source.render.opacity = 0.5;
});

Composite.add(world, box);

Event Object Properties

When the callback executes, it receives an event object with two primary properties:

Controlling Sleep Timing

A body goes to sleep once its motion drops below a specific speed threshold for a set number of updates. You can fine-tune when sleepStart triggers by modifying the sleepThreshold property on individual bodies or globally:

// Triggers sleep after 30 consecutive low-motion frames (default is 60)
box.sleepThreshold = 30;

A lower sleepThreshold makes the body enter sleep mode faster, triggering sleepStart more quickly after coming to a rest. If the body is disturbed by a collision or user interaction, it will automatically wake up and trigger a corresponding sleepEnd event.