How to Shift Center of Mass in Matter.js

This article explains how to modify the center of mass of a rigid body in the Matter.js 2D physics engine. By default, Matter.js calculates the center of mass automatically based on the geometric center of the body's vertices. You can alter this balance point using the built-in Body.setCentre method or by constructing compound bodies with weighted parts to simulate uneven weight distribution, self-righting objects, or irregular rotational behavior.

Method 1: Using Body.setCentre

The most direct way to change the center of mass is via the Matter.Body.setCentre function. This method shifts the body's center of mass relative to its current vertices without changing the visual rendering position of the body in default renderers.

const { Bodies, Body } = Matter;

// Create a standard rectangular body
const box = Bodies.rectangle(400, 200, 80, 80);

// Shift the center of mass 20 pixels to the right and 10 pixels down
// Setting the third argument to true applies the shift relative to the current center
Body.setCentre(box, { x: 20, y: 10 }, true);

Syntax and Parameters

Method 2: Creating Compound Bodies

Another approach is creating a compound body using Body.create({ parts: [...] }). Matter.js automatically computes a shared center of mass based on the positions and individual masses of the combined sub-parts.

const { Bodies, Body } = Matter;

// Create a main body part
const mainBody = Bodies.rectangle(400, 200, 100, 40);

// Create an invisible, heavy counterweight positioned off-center
const counterWeight = Bodies.circle(430, 200, 10, {
    mass: 10,
    render: { visible: false }
});

// Combine them into a single compound body
const weightedBody = Body.create({
    parts: [mainBody, counterWeight]
});

The composite body will naturally balance around the heavier part, shifting the rotational axis and center of gravity toward the counterweight.

Key Considerations