How to Create Compound Bodies in Matter.js
This guide explains how to combine multiple rigid shapes into a
single compound body using Matter.js. By utilizing the
parts property within Matter.Body.create, you
can bind distinct geometric forms—such as rectangles, circles, and
polygons—into a single physical object that rotates, collides, and moves
as one cohesive unit with an automatically calculated center of
mass.
Understanding Compound Bodies
In Matter.js, a compound body is a parent body composed of multiple sub-bodies called parts. The physics engine treats the entire collection as a single rigid body for collision detection, mass calculation, and movement, while retaining the individual geometries for accurate contact resolution.
Step-by-Step Implementation
1. Define the Individual Parts
First, instantiate the shapes you want to combine using the
Matter.Bodies module. Position them in world coordinates
where they should sit relative to one another.
const { Bodies, Body, Composite } = Matter;
// Create the individual shapes
const base = Bodies.rectangle(400, 300, 200, 40, {
render: { fillStyle: '#e74c3c' }
});
const tower = Bodies.rectangle(400, 250, 40, 100, {
render: { fillStyle: '#3498db' }
});
const cap = Bodies.circle(400, 180, 25, {
render: { fillStyle: '#2ecc71' }
});2. Group the Parts Using
Body.create
Pass the array of individual shapes to Body.create using
the parts property. When creating a compound body,
Matter.js automatically computes the aggregate center of mass and
realigns the sub-parts relative to this new center.
// Combine the shapes into one compound body
const compoundBody = Body.create({
parts: [base, tower, cap]
});3. Add the Compound Body to the World
Add only the parent compound body to the world. Do not add the individual parts separately, as doing so will duplicate them in the simulation.
// Add the compound body to the physics engine world
Composite.add(engine.world, compoundBody);Important Considerations
- Positioning After Creation: When
Body.createruns, it recalculates the body'spositionto match the collective center of mass. If you need to move or reposition the compound body after creation, useBody.setPosition(compoundBody, { x, y })rather than moving individual parts. - Mass and Inertia: The mass, area, and moment of
inertia are automatically summed from all assigned parts. You can
override these properties manually in the
Body.createoptions if custom physics behavior is required. - Collision Handling: Collision events will report
the compound body as the root
body, but the specific sub-shape involved in the contact can still be accessed via the event'spartreference.