How to Create a Polygon Body in Matter.js

This guide explains how to generate polygonal rigid bodies in the Matter.js 2D physics engine. You will learn how to create standard, symmetrical regular polygons using the built-in polygon factory method, as well as how to construct complex or irregular polygons using custom vertex coordinates and the required decomposition libraries.


Creating Regular Polygons

Matter.js provides a built-in method called Matter.Bodies.polygon to create regular polygons (shapes where all sides and angles are equal, such as triangles, pentagons, or hexagons).

Syntax

Matter.Bodies.polygon(x, y, sides, radius, [options]);

Example: Creating a Regular Hexagon

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

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

// Create a regular hexagon with 6 sides and a radius of 50px
const hexagon = Bodies.polygon(400, 200, 6, 50, {
    density: 0.001,
    frictionAir: 0.01,
    restitution: 0.6,
    render: {
        fillStyle: '#3498db',
        strokeStyle: '#2980b9',
        lineWidth: 2
    }
});

// Add the body to the world
Composite.add(world, hexagon);

Creating Irregular or Custom Polygons

To create a polygon with irregular dimensions or specific coordinates, use Matter.Bodies.fromVertices.

1. Define the Vertices

Vertices must be supplied as an array of vector objects containing x and y coordinates.

const vertices = [
    { x: 0, y: 0 },
    { x: 40, y: -20 },
    { x: 80, y: 0 },
    { x: 60, y: 60 },
    { x: 20, y: 60 }
];

2. Handle Concave Shapes (poly-decomp)

By default, physics engines require shapes to be convex. If your polygon is concave (it has an indentation), Matter.js relies on an external library called poly-decomp.js to automatically decompose the polygon into multiple convex parts.

Include the library before your Matter.js script:

<script src="https://cdn.jsdelivr.net/npm/poly-decomp@0.3.0/build/decomp.min.js"></script>

Then tell Matter.js to use it:

Matter.Common.setDecomp(decomp);

3. Instantiate the Body

const customPolygon = Bodies.fromVertices(400, 300, vertices, {
    isStatic: false,
    render: {
        fillStyle: '#e74c3c'
    }
});

Composite.add(world, customPolygon);

Creating Polygons from SVG Paths

You can also create polygonal bodies directly from SVG path strings using Matter.Vertices.fromPath.

const path = "M 0 0 L 50 0 L 25 50 Z";
const pathVertices = Matter.Vertices.fromPath(path);

const svgBody = Bodies.fromVertices(300, 200, pathVertices, {
    render: {
        fillStyle: '#2ecc71'
    }
});

Composite.add(world, svgBody);