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]);x: The horizontal position of the body's center of mass in pixels. Matter.js positions bodies from their center, not their top-left corner.y: The vertical position of the body's center of mass in pixels.width: The total width of the rectangle.height: The total height of the rectangle.options(optional): An object defining physical and visual properties.
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:
isStatic(boolean): Set totrueto keep the body fixed in place, making it ideal for walls, floors, and platforms.restitution(number): Controls elasticity. A value of0means no bounce, while1creates a fully elastic bounce.friction(number): Determines kinetic friction against other surfaces (default is0.1).angle(number): The initial rotation of the rectangle in radians.render(object): Controls styling, includingfillStyle(background color),strokeStyle(border color), andlineWidth.