Understanding Matter.Runner in Matter.js
In the Matter.js 2D physics engine, Matter.Runner is an
optional utility module designed to automate and manage the simulation
loop. This article explains the primary role of
Matter.Runner, how it regulates the timing and execution of
physics updates, and why it is commonly used instead of writing a manual
requestAnimationFrame loop.
The Core Purpose of Matter.Runner
At its core, a physics engine requires continuous updates over time
to calculate movement, collisions, and constraints. While
Matter.Engine manages the mathematical simulation of the
world, it does not run continuously on its own; it requires explicit
calls to Matter.Engine.update(engine, delta).
Matter.Runner bridges this gap by providing an automated
execution loop. It synchronizes the physics simulation with the
browser’s refresh rate via window.requestAnimationFrame,
repeatedly advancing the engine step by step without requiring
boilerplate loop code from the developer.
Key Responsibilities and Features
Timestep and Delta Management Physics engines can behave unpredictably if time intervals vary wildly between frames.
Matter.Runnerhandles delta timing to ensure consistent behavior. It normalizes delta variations, smooths out frame drops, and prevents the physics simulation from breaking or bodies tunneling through each other during momentary browser stutters.Loop Lifecycle Controls
Matter.Runnerprovides built-in methods to manage the state of the physics loop easily:Matter.Runner.run(runner, engine): Binds the runner to an engine and begins the loop.Matter.Runner.stop(runner): Pauses the execution loop, effectively freezing the physics simulation in place.Matter.Runner.start(runner): Resumes a stopped loop.
Event Dispatching The runner triggers lifecycle events—such as
beforeTick,tick, andafterTick—allowing developers to execute custom game logic, state checks, or external rendering updates at precise moments during each cycle.
Matter.Runner vs. Custom Loops
While Matter.Runner is suitable for most web-based
physics simulations, it is not mandatory. Developers building complex
games with their own centralized game loops (such as in Phaser or
PixiJS) often bypass Matter.Runner to manually call
Matter.Engine.update() within their own ticker.
However, for standalone projects, prototypes, or standard interactive
elements, Matter.Runner provides the simplest, most stable
way to drive the physics engine with built-in frame-rate smoothing and
low configuration overhead.