Create a Trapezoid Body in Matter.js

This guide explains how to create and configure a 2D trapezoid physics body using Matter.js. You will learn the syntax of the dedicated Bodies.trapezoid factory method, understand how the slope parameter controls the body's shape, and see a functional code implementation to add the body to your physics world.

The Bodies.trapezoid Method

Matter.js provides a built-in method in the Bodies module specifically designed for creating trapezoids:

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

Parameter Breakdown

Code Implementation

Below is a complete script demonstrating how to define and add a trapezoid body to a Matter.js world:

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

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

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

Render.run(render);

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

// 4. Create the trapezoid body
const trapezoidBody = Bodies.trapezoid(400, 300, 200, 100, 0.5, {
    isStatic: false,
    restitution: 0.6,
    render: {
        fillStyle: '#3498db'
    }
});

// 5. Create a static ground for the trapezoid to land on
const ground = Bodies.rectangle(400, 580, 810, 60, { isStatic: true });

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

Inverting a Trapezoid

By default, the narrower edge of the trapezoid sits at the top. To flip the shape so the wider edge is on top, provide a negative slope value (e.g., -0.5) or rotate the body after initialization using Matter.Body.rotate(trapezoidBody, Math.PI).