How to Create an Empty Composite in Matter.js

In Matter.js, a composite is an organizational container used to group together physics elements such as rigid bodies, constraints, and even nested composites. This guide provides a straightforward explanation of how to instantiate a new, empty composite using the Matter.Composite module, allowing you to dynamically manage and manipulate grouped physics entities in your simulation.

The Composite.create Method

To create an empty composite, you use the Composite.create() method provided by Matter.js. When invoked without any arguments, or with an empty configuration object, it initializes an empty container.

// Import the Composite module from Matter.js
const { Composite } = Matter;

// Create a new, empty composite
const myComposite = Composite.create();

Providing Configuration Options

You can also pass an optional configuration object to Composite.create() to assign properties such as a custom label for tracking or debugging purposes:

const myComposite = Composite.create({
    label: 'EmptyObstacleGroup'
});

By default, the newly created composite contains empty arrays for bodies, constraints, and composites.

Adding Objects to the Empty Composite

Once the empty composite is created, you can populate it dynamically using Composite.add().

const { Composite, Bodies } = Matter;

// 1. Create the empty composite
const container = Composite.create();

// 2. Create a body
const box = Bodies.rectangle(400, 200, 80, 80);

// 3. Add the body to the composite
Composite.add(container, box);

Adding the Composite to the Matter.js World

Because the top-level engine.world is itself a composite, you integrate your custom composite into the simulation by adding it directly to the world:

// Add the composite (and all items within it) to the physics world
Composite.add(engine.world, container);