Calculate Compound Body Mass in Matter.js
This article explains how to determine the total mass of a compound body in Matter.js. You will learn how Matter.js natively handles mass aggregation across multiple shapes, how to read the total mass directly from the body instance, and how to manually calculate or recalculate the combined mass using the body's individual constituent parts.
Direct Access via the Parent Body
Matter.js automatically computes the total mass of a compound body when it is initialized or when its parts are updated. In a compound body, the parent container stores the aggregated mass of all attached sub-shapes.
You can read the total mass directly via the mass
property:
// Access the total combined mass
const totalMass = compoundBody.mass;
console.log(`Total Mass: ${totalMass}`);When you define a compound body using
Body.create({ parts: [...] }), the physics engine
calculates the mass of each individual part based on its area and
density, sums them together, and assigns the result to the main body's
mass property.
Manually Calculating Mass from Sub-Parts
If you need to verify or manually compute the sum of the masses, you
must access the body's parts array.
In Matter.js, body.parts contains all elements of the
compound body, but body.parts[0] is always a
self-reference to the parent body itself. The actual physical
sub-shapes start at index 1.
To calculate the total mass manually, exclude the first element and
sum the mass of the remaining parts:
function calculateCompoundMass(body) {
// If the body has no child parts, return its own mass
if (!body.parts || body.parts.length <= 1) {
return body.mass;
}
// Slice from index 1 to ignore the parent reference
const childParts = body.parts.slice(1);
// Sum the mass of each part
const totalMass = childParts.reduce((accumulator, part) => {
return accumulator + part.mass;
}, 0);
return totalMass;
}
const calculatedMass = calculateCompoundMass(compoundBody);
console.log(`Calculated Total Mass: ${calculatedMass}`);Updating Mass When Parts Change
If you modify the density or size of an individual part after
creating a compound body, the parent body's total mass will not update
automatically. To recalculate the mass, re-apply the parts to the parent
body using Body.setParts():
const { Body } = Matter;
// Modify a specific part's density
Body.setDensity(compoundBody.parts[1], 0.005);
// Re-apply parts to recalculate total mass, center of mass, and inertia
Body.setParts(compoundBody, compoundBody.parts);
console.log(`Updated Total Mass: ${compoundBody.mass}`);Alternatively, you can manually override the entire compound body's
mass using Body.setMass(compoundBody, newMass), which
scales the mass and inertia without altering individual part
geometries.