How to Create Matter.Runner in Matter.js
This article provides a concise guide on creating and utilizing a
Matter.Runner instance in Matter.js. You will learn the
purpose of the runner module, how to instantiate it with custom or
default options, how to bind it to a physics engine to manage the
simulation loop, and how to stop it when necessary.
Understanding Matter.Runner
In Matter.js, Matter.Runner is an optional utility that
provides an automated game loop. It handles calling
Matter.Engine.update along with
requestAnimationFrame continuously, ensuring that the
physics simulation advances smoothly over time at a consistent frame
rate.
Creating the Runner Instance
To create a new runner instance, use the
Matter.Runner.create() method. This method accepts an
optional configuration object.
// Import Matter modules if using an ES module environment
const { Engine, Runner } = Matter;
// Create an engine first
const engine = Engine.create();
// Create a runner instance with default settings
const runner = Runner.create();Configuring Runner Options
You can pass an options object to Runner.create() to
fine-tune its execution:
isFixed(boolean): Set totrueto use a fixed time step regardless of frame rate. Defaults tofalse.delta(number): The fixed time step size in milliseconds (default is1000 / 60, roughly 16.666ms).
const runner = Runner.create({
isFixed: true,
delta: 1000 / 60
});Starting and Stopping the Runner
Once the runner is instantiated, you must start it by passing both
the runner and the engine to Matter.Runner.run():
// Start the simulation loop
Runner.run(runner, engine);To pause or permanently stop the loop, use
Matter.Runner.stop():
// Stop the simulation loop
Runner.stop(runner);Complete Implementation Example
Below is a complete, minimal example demonstrating the creation and
execution of a Matter.Runner:
const { Engine, Render, World, Bodies, Runner } = Matter;
// Initialize the engine
const engine = Engine.create();
// Create the renderer
const render = Render.create({
element: document.body,
engine: engine
});
// Add a simple body to the world
const box = Bodies.rectangle(400, 200, 80, 80);
const ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });
World.add(engine.world, [box, ground]);
// Run the renderer
Render.run(render);
// Create and run the Matter.Runner
const runner = Runner.create();
Runner.run(runner, engine);