How to Add Constraints to a Matter.js Composite

This guide explains how to create and attach physical constraints to a Composite in Matter.js. By utilizing the Matter.Constraint module alongside Matter.Composite.add, you can easily establish fixed joints, elastic springs, and pin connections between multiple rigid bodies or anchor points within your physics simulation.

Prerequisites and Modules

To work with constraints and composites, ensure you have imported or referenced the essential Matter.js modules:

const { Engine, Render, Runner, Bodies, Composite, Constraint } = Matter;

Creating Bodies and Constraints

A constraint in Matter.js specifies a relationship between two bodies, or between a single body and a fixed world position. You define a constraint using the Constraint.create() method.

1. Connecting Two Bodies

To link two moving bodies together, specify both bodyA and bodyB:

// Create two dynamic bodies
const boxA = Bodies.rectangle(300, 200, 50, 50);
const boxB = Bodies.rectangle(400, 200, 50, 50);

// Create a constraint connecting boxA and boxB
const chainLink = Constraint.create({
    bodyA: boxA,
    bodyB: boxB,
    length: 100,
    stiffness: 0.9
});

2. Pinning a Body to a World Position

To anchor a body to a fixed point in the scene, provide bodyA and a static coordinate via pointB:

const pendulumBall = Bodies.circle(400, 300, 20);

const pin = Constraint.create({
    pointA: { x: 400, y: 100 }, // Fixed world anchor
    bodyB: pendulumBall,
    pointB: { x: 0, y: 0 },      // Offset on bodyB relative to its center
    stiffness: 1,
    length: 200
});

Adding Constraints to a Composite

In Matter.js, the scene world (engine.world) is itself a Composite. You can add constraints directly to the main world or to a custom nested composite using Composite.add().

Adding to the World Composite

Pass the world composite as the first argument, followed by the bodies and the constraint (either as individual arguments or inside an array):

const engine = Engine.create();
const world = engine.world;

// Add bodies and the constraint simultaneously
Composite.add(world, [boxA, boxB, chainLink]);

Adding to a Custom Composite

Group related components into a dedicated composite before adding the composite to the world:

// Create a separate composite for a bridge or rope
const ropeComposite = Composite.create({ label: 'Rope' });

// Add bodies and constraints to the custom composite
Composite.add(ropeComposite, [boxA, boxB, chainLink]);

// Add the custom composite to the engine world
Composite.add(world, ropeComposite);

Common Constraint Properties

When defining a constraint, adjust these key options: