How to Create a Rectangular Body in Matter.js

This article explains how to create a rectangular rigid body using Matter.js, a 2D physics engine for the web. You will learn the core method used to instantiate rectangles, understand the required coordinate parameters, configure custom physical properties, and add the finished body to your physics simulation.

To create a rectangular body in Matter.js, use the Bodies.rectangle() method provided by the Matter.Bodies module.

Syntax and Parameters

The basic syntax for creating a rectangle is:

Matter.Bodies.rectangle(x, y, width, height, [options]);

Basic Implementation

Here is a standard example that creates a dynamic rectangle and a static ground rectangle:

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

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

// Create a dynamic falling box
const box = Bodies.rectangle(400, 200, 80, 80, {
  restitution: 0.8, // Bounciness
  friction: 0.05
});

// Create a static ground rectangle
const ground = Bodies.rectangle(400, 580, 810, 60, {
  isStatic: true // Prevents the body from moving or falling
});

// Add the bodies to the world
Composite.add(engine.world, [box, ground]);

// Run the engine and renderer
Render.run(render);
Runner.run(Runner.create(), engine);

Useful Body Options

When passing the options object to Bodies.rectangle(), you can customize how the rectangle interacts and appears: