Pause Matter.js Engine on Specific Collision
Pausing the physics simulation in Matter.js during a specific
collision event involves listening for collision events, identifying the
target bodies, and halting the runner. This guide explains how to
monitor collision pairs using the collisionStart event,
verify specific body labels, and stop the Matter.Runner to
immediately freeze the simulation state.
Step 1: Label Your Bodies
To detect when specific objects collide, assign distinct labels or unique properties to the bodies when creating them.
const player = Matter.Bodies.circle(100, 100, 20, { label: 'player' });
const hazard = Matter.Bodies.rectangle(100, 300, 50, 50, { label: 'hazard', isStatic: true });
Matter.Composite.add(engine.world, [player, hazard]);Step 2: Listen for
the collisionStart Event
Matter.js dispatches collision events via Matter.Events.
Use the collisionStart event on your engine to check pairs
of bodies that have just made contact.
Matter.Events.on(engine, 'collisionStart', (event) => {
const pairs = event.pairs;
for (let i = 0; i < pairs.length; i++) {
const { bodyA, bodyB } = pairs[i];
// Check if the collision is between the player and the hazard
if (
(bodyA.label === 'player' && bodyB.label === 'hazard') ||
(bodyA.label === 'hazard' && bodyB.label === 'player')
) {
pauseSimulation();
break;
}
}
});Step 3: Stop the Runner
The standard way to pause the engine loop in Matter.js is by calling
Matter.Runner.stop(). This stops updating the physics
engine while keeping the current world state intact.
// Initialize the runner
const runner = Matter.Runner.create();
Matter.Runner.run(runner, engine);
// Function to pause the simulation
function pauseSimulation() {
Matter.Runner.stop(runner);
console.log('Simulation paused due to collision.');
}To resume the simulation later, call
Matter.Runner.run(runner, engine).
Alternative: Pausing via Time Scale
If you are using a custom animation loop instead of
Matter.Runner, you can pause the simulation by setting the
engine's time scale to zero:
function pauseSimulation() {
engine.timing.timeScale = 0;
}Setting engine.timing.timeScale = 1 will restore normal
simulation speed.