Matter.World.add Parameters in Matter.js
This article explains the parameters accepted by the
Matter.World.add function in the Matter.js 2D physics
engine. It breaks down the function signature, details the two primary
arguments it accepts, and lists the specific physics object types that
can be registered into a simulation world.
Function Signature
In Matter.js, Matter.World inherits from
Matter.Composite. The Matter.World.add method
uses the following signature:
Matter.World.add(world, object)The method accepts two arguments: the target world composite and the
object (or array of objects) to be simulated. It returns the modified
world instance to allow method chaining.
Parameter 1: world
- Type:
Matter.World(orMatter.Composite) - Description: The root world instance of the physics
engine (commonly accessed via
engine.world). This composite acts as the container for all physical entities participating in the simulation.
Parameter 2: object
- Type:
Matter.Body|Matter.Constraint|Matter.Composite|Array<Matter.Body | Matter.Constraint | Matter.Composite> - Description: The entity or list of entities you want to introduce to the physics world.
The object argument accepts several specific Matter.js
types:
1. Rigid Bodies
(Matter.Body)
Single rigid bodies created using Matter.Body.create()
or helper methods from Matter.Bodies (such as
rectangle, circle, polygon, or
fromVertices).
- Example:
const box = Matter.Bodies.rectangle(400, 200, 80, 80); Matter.World.add(engine.world, box);
2. Constraints
(Matter.Constraint)
Joints, springs, elastic connections, or pins connecting two bodies (or one body and a fixed world point).
- Example:
const spring = Matter.Constraint.create({ bodyA: bodyA, bodyB: bodyB, stiffness: 0.05 }); Matter.World.add(engine.world, spring);
3. Mouse Constraints
(Matter.MouseConstraint)
A specialized constraint wrapper that links canvas mouse interactions directly to bodies within the world.
- Example:
const mouseConstraint = Matter.MouseConstraint.create(engine, { element: canvas }); Matter.World.add(engine.world, mouseConstraint);
4. Composites
(Matter.Composite)
Higher-level containers or groups containing multiple bodies, constraints, or other nested composites (such as car models, chains, or ragdolls).
- Example:
const stack = Matter.Composites.stack(20, 20, 10, 5, 0, 0, (x, y) => { return Matter.Bodies.circle(x, y, 20); }); Matter.World.add(engine.world, stack);
5. Arrays of Valid Objects
Instead of calling Matter.World.add repeatedly, you can
pass an array containing any combination of bodies, constraints, and
composites in a single call.
- Example:
Matter.World.add(engine.world, [ ground, boxA, boxB, ropeConstraint, mouseConstraint ]);