Understanding Center of Mass in Matter.js

In Matter.js, the center of mass represents the physical balance point of a rigid body around which all linear motion, rotations, and applied torques revolve. This article explains what the center of mass represents within the 2D physics engine, how it directly corresponds to a body's coordinates, its effect on physical interactions, and how you can adjust or offset it to create realistic behavioral simulations.

The Role of the Center of Mass

In Matter.js, a body's position property (body.position) is precisely its center of mass. Unlike traditional DOM elements or canvas drawing logic that often measure coordinates from the top-left corner or an arbitrary bounding box origin, Matter.js defines every rigid body in 2D space relative to its center of mass.

When you create a standard primitive using Matter.Bodies.rectangle or Matter.Bodies.circle, the engine automatically assigns the center of mass to the geometric center (centroid) of the shape. For arbitrary polygons defined by a custom array of vertices, the engine computes the centroid of the polygon geometry and sets that point as the body’s initial position.

How the Center of Mass Dictates Physics

The center of mass governs how a body interacts dynamically in the physics world:

Center of Mass in Compound Bodies

When multiple bodies are grouped into a compound body using Matter.Body.create({ parts: [...] }), Matter.js automatically recalculates the global center of mass.

The engine evaluates the mass and position of each individual part to determine the overall weighted balance point. Once established, the compound body's position shifts to this collective center, and all individual sub-parts have their relative vertices adjusted so that rotation and linear dynamics occur realistically around the unified center of mass.

Modifying and Offsetting the Center of Mass

By default, Matter.js assumes uniform density across a body's geometry, which places the center of mass at the centroid. However, certain simulations require an uneven weight distribution, such as a weighted punching bag, a self-righting buoy, or a car chassis.

You can alter the center of mass using the built-in function:

Matter.Body.setCentre(body, centre, relative);

Calling setCentre shifts the body's internal vertices relative to the position vector without moving the body visibly in the world. This shifts the internal pivot point, causing the body to naturally swing, settle, or rotate around the newly designated center of mass.