How to Add Bodies to a Composite in Matter.js

Matter.js uses composites as containers to group bodies, constraints, and even nested composites into single manageable structures. This guide demonstrates how to instantiate a custom Composite, create physics bodies, and populate the container using the built-in Composite.add method so they can be simulated together in your physics world.

1. Create a Custom Composite

You initialize a standalone composite using the Matter.Composite.create() method. You can optionally pass configuration options, such as a label, to help identify the group.

const { Composite, Bodies, Engine } = Matter;

// Create a custom composite container
const customComposite = Composite.create({
    label: 'CarStructure'
});

2. Define the Bodies

Create standard Matter.js rigid bodies using the Bodies factory module. These bodies will later be added to your custom composite.

// Create individual bodies
const chassis = Bodies.rectangle(400, 200, 100, 20, { label: 'Chassis' });
const wheelA = Bodies.circle(370, 220, 15, { label: 'LeftWheel' });
const wheelB = Bodies.circle(430, 220, 15, { label: 'RightWheel' });

3. Add Bodies to the Composite

Use Composite.add() to insert the bodies into your composite. The method accepts the target composite as the first argument and either a single body or an array of bodies as the second argument.

// Add multiple bodies at once
Composite.add(customComposite, [chassis, wheelA, wheelB]);

Adding Bodies Individually

// Add bodies one by one
Composite.add(customComposite, chassis);
Composite.add(customComposite, wheelA);
Composite.add(customComposite, wheelB);

4. Add the Custom Composite to the World

Custom composites are not simulated until they are attached to the root composite of the engine, which is engine.world. Add your custom composite directly to engine.world using the same Composite.add() function.

const engine = Engine.create();

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

Complete Implementation Example

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

// Setup engine and renderer
const engine = Engine.create();
const render = Render.create({
    element: document.body,
    engine: engine,
    options: { width: 800, height: 600, wireframes: false }
});

Render.run(render);
Runner.run(Runner.create(), engine);

// 1. Initialize the custom composite
const customComposite = Composite.create({ label: 'MyGroup' });

// 2. Create the bodies
const box1 = Bodies.rectangle(400, 100, 50, 50);
const box2 = Bodies.rectangle(400, 50, 50, 50);
const ground = Bodies.rectangle(400, 590, 810, 60, { isStatic: true });

// 3. Add the boxes to the custom composite
Composite.add(customComposite, [box1, box2]);

// 4. Add the composite and other elements to the world
Composite.add(engine.world, [customComposite, ground]);