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
Body.setCentre(body, centre, [relative=false])body: The targetMatter.Bodyinstance.centre: A vector object{ x: number, y: number }defining the new coordinates.relative: A boolean flag. When set totrue, thecentrevector acts as an offset added to the current position. Whenfalse(default),centrerepresents the exact absolute world coordinate.
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
- Moment of Inertia: Shifting the center of mass
affects the rotational inertia of the body. If rotation feels unnatural
after a shift, adjust the body's inertia using
Body.setInertia(body, newInertia). - Renderer Alignment: If you are using custom canvas
rendering or integrating with a rendering library like PixiJS or
Three.js, ensure you offset your visual sprites to align with
body.position, which tracks the shifted center of mass rather than the geometric center.