How to Use the sleepEnd Event in Matter.js

This guide explains how to implement and handle the sleepEnd event in Matter.js. By default, Matter.js allows rigid bodies to "sleep" when they come to a complete rest, which optimizes physics calculations and saves processing power. The sleepEnd event triggers immediately when a sleeping body is awakened by a collision, an applied force, or manual state change. Below, you will learn how to enable sleeping in the engine, attach the event listener, and handle awake transitions in your physics simulations.

Step 1: Enable Sleeping on the Engine

Sleeping is disabled by default in Matter.js. To allow bodies to sleep and subsequently wake up, you must explicitly enable the feature when creating the engine or by updating the engine instance:

// Option A: Enable during engine creation
const engine = Matter.Engine.create({
  enableSleeping: true
});

// Option B: Enable on an existing engine
engine.enableSleeping = true;

Step 2: Create a Body Capable of Sleeping

Bodies will naturally fall asleep after remaining stationary for a short duration. You can configure sleep thresholds or manually wake/sleep a body:

const box = Matter.Bodies.rectangle(400, 200, 80, 80, {
  restitution: 0.5,
  sleepThreshold: 60 // Number of idle updates before falling asleep
});

Matter.Composite.add(engine.world, box);

Step 3: Listen for the sleepEnd Event

You can attach the sleepEnd event directly to an individual body or globally to the engine using Matter.Events.on.

Method A: Listening on a Specific Body

Use this approach when you want to handle wake-up logic for a specific object, such as changing its color or playing a sound effect:

Matter.Events.on(box, 'sleepEnd', function(event) {
  console.log('The box has awakened!');
  // The event source is the body that woke up
  const body = event.source;
  body.render.fillStyle = '#ff0000'; // Change color to indicate it is active
});

Method B: Listening Globally via the Engine

Use this approach if you want a centralized handler to monitor any body that wakes up across the entire physics world:

Matter.Events.on(engine, 'sleepEnd', function(event) {
  const body = event.source;
  console.log(`Body with ID ${body.id} has woken up.`);
});

Manually Waking a Body

If you want to trigger the sleepEnd event programmatically, you can wake a sleeping body using Matter.Sleeping.set:

// Force the body awake, triggering the sleepEnd event
Matter.Sleeping.set(box, false);

Common Use Cases