Matter.js: How Changing Density Affects Mass
In the Matter.js 2D physics engine, a rigid body's mass is directly
tied to its density and geometric area through the formula
mass = density * area. When you adjust the density of a
body, Matter.js recalculates its total mass and inverse mass while
keeping its physical dimensions unchanged. This guide explains the
internal relationship between density and mass in Matter.js, how to
modify density in code, and the resulting effects on the physics
simulation.
The Mathematical Relationship Between Density and Mass
Matter.js automatically computes the geometric area of a body upon
creation based on its vertices or shape definition (such as rectangles
or circles). By default, all bodies are initialized with a standard
density (typically 0.001).
The engine calculates mass using the following relationship:
\[\text{mass} = \text{density} \times \text{area}\]
Because the area represents the static geometric footprint of the shape, mass scales linearly with density:
- Increasing density proportionally increases the body's mass.
- Decreasing density proportionally decreases the body's mass.
Updating Density Programmatically
To change density after a body has been instantiated, use the
Matter.Body.setDensity method rather than directly mutating
the property:
// Setting the density of an existing body
Matter.Body.setDensity(myBody, 0.005);When Body.setDensity is executed, Matter.js carries out
three automatic updates:
- Multiplies the new density value by the existing
body.area. - Updates
body.massto the resulting value. - Updates
body.inverseMassto1 / mass(used internally for performance during physics computations).
Alternatively, if you use
Matter.Body.setMass(myBody, newMass), the reverse
calculation occurs: Matter.js updates the mass directly and recalculates
body.density as newMass / body.area.
Simulation Impacts of Changing Density
Altering a body’s density directly alters its physical behavior in the simulation without changing how it looks visually:
- Collision Momentum: Heavier bodies (higher density) possess more momentum at the same velocity. In a collision between a high-density body and a low-density body, the heavier object will deflect less and impart more force to the lighter object.
- Constraints and Springs: Matter.js constraints (such as ropes or springs) behave differently under varying loads. Bodies with higher density will cause constraints to stretch or deform more under force.
- Applied Forces: When using
Matter.Body.applyForce, acceleration is governed by Newton's second law (\(F = ma\), or \(a = F/m\)). Increasing density increases mass, meaning the same applied force will produce less acceleration. - Rotational Inertia: Changing density also alters
the body's moment of inertia (
body.inertia), making denser objects harder to rotate using equivalent angular forces.