Understanding Matter.js Body Parts Array
The parts array in Matter.js is the foundational
mechanism used to create and manage compound bodies, which are single
physics bodies composed of multiple geometric shapes. This article
explains the technical purpose of the parts array, how
Matter.js structures parent-child relationships within it, and how it
enables complex collision geometries and dynamic physical property
calculations.
In Matter.js, individual standard bodies must be convex polygons. To
construct complex or concave structures—such as a hollow container, an
"L" shape, or a vehicle chassis—developers must combine multiple convex
bodies into a single compound body. The parts array holds
the references to all the individual sub-bodies that constitute this
unified entity.
The internal structure of the parts array follows a
strict convention:
- Index 0 (
parts[0]): This is always a self-reference to the parent body itself. - Indices 1 and beyond (
parts[1],parts[2], etc.): These represent the actual sub-parts (or child bodies) that define the physical shape and collision boundaries of the compound body.
When multiple bodies are grouped into a compound body, Matter.js
recalculates the parent body's physical properties based on the combined
attributes of everything in the parts array. The physics
engine automatically determines:
- Center of Mass: The parent's position is shifted to the collective center of mass of all individual parts.
- Mass and Density: The total mass equals the sum of the masses of each part in the array.
- Moment of Inertia: Rotational inertia is calculated across all parts relative to the new collective center of mass.
- Bounds and Vertices: The broadphase collision bounds of the parent are dynamically updated to envelop every part in the array.
During the collision detection phase, the physics engine checks
collisions against each individual child part in the parts
array using the Separating Axis Theorem (SAT). However, when a collision
response (impulse or force) is applied, it is applied directly to the
root parent body, causing the entire compound structure to move and
rotate as a single rigid object.
To safely configure or modify the parts array,
developers should use the built-in
Body.setParts(body, parts) method rather than mutating the
array directly. This method ensures that vertex offsets, total mass,
inertia, and position relative to the center of mass are correctly
recalculated and synchronized across the physics world.