How to Create a Circular Body in Matter.js
This guide provides a straightforward walkthrough on creating, configuring, and adding a circular rigid body to a 2D physics simulation using Matter.js. You will learn the exact method syntax, parameter definitions, and how to customize the physical properties of the circle.
In Matter.js, circular rigid bodies are created using the built-in
Bodies.circle factory method provided by the
Matter.Bodies module.
The Bodies.circle
Method Syntax
The basic syntax for instantiating a circle is:
Matter.Bodies.circle(x, y, radius, [options], [maxSides]);Parameters
x(Number): The x-coordinate of the circle's center point in the world space.y(Number): The y-coordinate of the circle's center point in the world space.radius(Number): The radius of the circle in pixels.options(Object, optional): An object specifying properties to override default physics and appearance settings (e.g., density, friction, restitution, render styles).maxSides(Number, optional): An integer defining the maximum number of sides used to approximate the circle. If omitted, Matter.js automatically determines a suitable value based on the radius.
Implementation Example
To create a circle and include it in your physics world:
// Alias Matter.js modules
const { Engine, Render, Runner, Bodies, Composite } = Matter;
// Create engine and world
const engine = Engine.create();
const world = engine.world;
// Define circle properties
const x = 400;
const y = 200;
const radius = 30;
// Create the circular body with custom physics options
const circle = Bodies.circle(x, y, radius, {
restitution: 0.8, // Bounciness (0 = no bounce, 1 = full bounce)
friction: 0.05, // Surface friction
density: 0.001, // Mass density
isStatic: false, // Set to true if the body should not move
render: {
fillStyle: '#3498db',
strokeStyle: '#2980b9',
lineWidth: 2
}
});
// Add the circle to the world
Composite.add(world, circle);Key Considerations
- Positioning: Unlike HTML DOM elements, which
typically measure position from the top-left corner, Matter.js positions
bodies using their center of mass. Setting
x: 100andy: 100positions the exact center of the circle at(100, 100). - Static Circles: To turn a circular body into an
immovable obstacle (such as a peg or bumper), include
isStatic: truein theoptionsobject. - Collision Detection: Matter.js uses optimized circle-to-circle and circle-to-polygon collision algorithms, making circles computationally efficient compared to complex concave shapes.