How to Use Matter.Composites.chain in Matter.js

This guide explains how to use the Matter.Composites.chain function in Matter.js to link multiple rigid bodies together into cohesive structures like chains, ropes, or bridges. You will learn the function's syntax, the required parameters, how to generate and link bodies sequentially, and how to anchor the chain to a fixed point in your physics world.

Understanding Matter.Composites.chain

The Matter.Composites.chain function is a utility method that automatically generates constraints (springs or joints) between consecutive bodies contained within a single Matter.Composite. Instead of manually instantiating individual Matter.Constraint objects between each pair of bodies, chain iterates through the composite's bodies array and links each body to the next.

Method Signature

Matter.Composites.chain(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options);

Parameters

Step-by-Step Implementation

1. Create a Stack of Bodies

The easiest way to prepare bodies for chaining is with Matter.Composites.stack. This creates a series of bodies placed in a row or column.

const { Composite, Composites, Bodies } = Matter;

// Create a row of rectangles
const group = Matter.Body.nextGroup(true); // Prevents collisions between links
const chainComposite = Composites.stack(200, 100, 8, 1, 10, 0, (x, y) => {
    return Bodies.rectangle(x, y, 40, 20, { 
        collisionFilter: { group: group },
        chamfer: 5
    });
});

2. Apply the Chain

Call Composites.chain on the composite. Define connection offsets so the right side of one body connects to the left side of the following body.

// Link right edge (offset 0.5) of Body A to left edge (offset -0.5) of Body B
Composites.chain(chainComposite, 0.5, 0, -0.5, 0, {
    stiffness: 0.9,
    length: 2,
    render: {
        visible: true,
        lineWidth: 2,
        strokeStyle: '#ffffff'
    }
});

3. Anchor the Chain (Optional)

Chains will fall freely under gravity unless anchored. To secure an end, add a constraint between a fixed point (or static body) and the first body in the chain:

const { Constraint } = Matter;

const anchor = Constraint.create({
    pointA: { x: 200, y: 100 },
    bodyB: chainComposite.bodies[0],
    pointB: { x: -20, y: 0 },
    stiffness: 1
});

Composite.add(chainComposite, anchor);

4. Add the Composite to the World

Finally, add the completed composite to your engine's world:

Composite.add(engine.world, chainComposite);

Practical Tips for Realistic Chains