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:

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:

  1. Multiplies the new density value by the existing body.area.
  2. Updates body.mass to the resulting value.
  3. Updates body.inverseMass to 1 / 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: