How to Add Multiple Bodies in Matter.js

This guide explains how to efficiently add multiple rigid bodies to a Matter.js physics simulation in a single operation. You will learn how to use the Composite.add method with an array, understand the performance benefits of bulk additions over individual calls, and review practical code examples to structure and populate your physics world cleanly.

Using Composite.add with an Array

In Matter.js, the standard way to add entities to a physics world is through the Matter.Composite.add function. Rather than passing single bodies one by one, you can pass an array containing all of your bodies directly to the composite.

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

// Initialize engine and world
const engine = Engine.create();
const world = engine.world;

// Create multiple bodies
const boxA = Bodies.rectangle(400, 200, 80, 80);
const boxB = Bodies.rectangle(450, 50, 80, 80);
const ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });

// Add all bodies at once by passing an array
Composite.add(world, [boxA, boxB, ground]);

Note: While older documentation often uses World.add(world, [...]), World is simply an alias for Composite. Using Composite.add is the current best practice in modern Matter.js.

Generating and Adding Bodies Dynamically

When working with large numbers of objects, you can programmatically populate an array using loops or array methods, then add the entire collection in a single call.

const stack = [];
const rows = 5;
const cols = 5;
const size = 40;

for (let i = 0; i < rows; i++) {
  for (let j = 0; j < cols; j++) {
    const x = 300 + j * (size + 5);
    const y = 100 + i * (size + 5);
    stack.push(Bodies.rectangle(x, y, size, size));
  }
}

// Add the entire generated set to the world
Composite.add(world, stack);

Why Add Bodies in Batches?

Adding bodies in bulk provides two key advantages:

  1. Performance: Every call to Composite.add triggers internal events, recalculations of composite bounds, and updates to the spatial indexing system. Passing an array reduces this overhead to a single composite update pass.
  2. Code Maintainability: Grouping bodies into logical arrays (such as static level geometry, interactive items, or obstacles) allows you to organize your scene setup cleanly and make dynamic removals or modifications easier later.