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
x(Number): The horizontal coordinate for the center of the body.y(Number): The vertical coordinate for the center of the body.width(Number): The total width of the trapezoid base.height(Number): The total height of the trapezoid.slope(Number): A float value between0and1defining the incline of the sides. A slope of0creates a standard rectangle, while a slope of1creates a triangle. Values between0and1(such as0.5) produce a standard trapezoid.options(Object, optional): Additional Matter.js body properties, such asisStatic,friction,restitution, andrenderstyling.
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).