How to Create a New Matter.js Engine Instance
Matter.js is a widely used 2D physics engine for the web that handles
rigid-body simulations, collisions, and constraints. This article
explains how to instantiate and configure a new Matter.js
Engine instance, integrate it with a world and runner, and
customize core simulation properties such as gravity and timing.
Step 1: Install or Import Matter.js
Before creating an engine, include Matter.js in your project. You can install it via npm:
npm install matter-jsOr load it via a CDN in your HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>Step 2: Use
Engine.create()
The Engine module is responsible for managing the
physics simulation update loop and world state. To instantiate a new
engine, use the Matter.Engine.create() method.
// Import modules if using ES modules
import Matter from 'matter-js';
// Module aliases
const Engine = Matter.Engine;
// Create a new engine instance
const engine = Engine.create();Step 3: Complete Working Implementation
Creating an engine alone does not display or continuously update the
simulation. You typically combine the Engine with a
Render (for visuals) and a Runner (for the
update loop).
import { Engine, Render, Runner, Bodies, Composite } from 'matter-js';
// 1. Create the engine instance
const engine = Engine.create();
// 2. Create a renderer (optional, primarily for debugging/viewing)
const render = Render.create({
element: document.body,
engine: engine,
options: {
width: 800,
height: 600,
wireframes: false
}
});
// 3. Add bodies to the engine's world
const box = Bodies.rectangle(400, 200, 80, 80);
const ground = Bodies.rectangle(400, 590, 810, 60, { isStatic: true });
Composite.add(engine.world, [box, ground]);
// 4. Run the renderer
Render.run(render);
// 5. Create and start the runner to update the engine
const runner = Runner.create();
Runner.run(runner, engine);Step 4: Configuring Engine Options
You can customize the engine's behavior by passing an options object
to Engine.create(options). Common configuration options
include:
gravity: Controls the directional pull of the world.timing.timeScale: Modifies the speed of simulation updates (e.g.,0.5for half-speed).enableSleeping: Improves performance by putting stationary bodies to sleep.
const engine = Engine.create({
enableSleeping: true,
gravity: {
x: 0,
y: 0.5, // Reduce downward gravity (default is 1)
scale: 0.001
},
timing: {
timeScale: 1 // Simulation speed multiplier
}
});You can also modify these values on the instance directly at any point during runtime:
engine.gravity.y = 0; // Disable vertical gravity dynamically