How to Add a Body to the World in Matter.js

This guide explains how to create a single rigid body and add it to a physics world using Matter.js. You will learn the modern syntax using the Composite module, see a complete code example, and understand the core methods required to get your physics objects rendering and interacting on the screen.

Step 1: Create a Body

Before you can add an object to your world, you must define it using the Matter.Bodies module. Matter.js provides several factory methods to create standard shapes, such as rectangles, circles, and polygons.

// Create a rectangular body
// Parameters: (x-position, y-position, width, height, [options])
const box = Matter.Bodies.rectangle(400, 200, 80, 80, {
    restitution: 0.8 // Adds bounciness
});

Step 2: Add the Body to the World

To introduce the body to the physics simulation, add it to the engine's world instance using Matter.Composite.add. While older documentation references Matter.World.add, Matter.Composite.add is the current, standard approach.

// Add the created body to the engine's world
Matter.Composite.add(engine.world, box);

Complete Working Example

Below is a minimal setup that initializes the engine, renderer, runner, and adds a single falling body along with a static ground body.

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

// 1. Create an engine
const engine = Engine.create();

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

Render.run(render);

// 3. Create a runner
const runner = Runner.create();
Runner.run(runner, engine);

// 4. Create a single dynamic body and a static ground
const fallingBox = Bodies.rectangle(400, 100, 50, 50, {
    render: {
        fillStyle: '#e74c3c'
    }
});

const ground = Bodies.rectangle(400, 580, 810, 60, { 
    isStatic: true 
});

// 5. Add the single dynamic body to the world
Composite.add(engine.world, fallingBox);

// Add the ground so the body does not fall off-screen
Composite.add(engine.world, ground);

Key Considerations