Can a Body Have Negative Mass in Matter.js?

Matter.js does not functionally support negative mass. While the JavaScript runtime allows you to assign a negative number to a body's mass property, doing so breaks the underlying physics equations, leading to inverted collision responses, unstable acceleration, and simulation crashes. This article explains how Matter.js processes mass, why negative values corrupt the engine's solver, and the proper alternatives for simulating negative-mass effects like antigravity.

How Matter.js Handles Mass

In Matter.js, a body's mass directly dictates how it responds to forces and collisions. When you define or update a body's mass using Body.setMass(body, mass), the engine calculates its inverse mass:

\[\text{inverseMass} = \frac{1}{\text{mass}}\]

The engine uses inverseMass rather than mass itself for constraint solving and collision resolution. Standard rigid-body physics calculations rely on mass being a strictly positive number. For immobile objects, Matter.js uses an infinite mass (mass = Infinity), which results in an inverseMass of 0, effectively preventing forces from moving the body.

What Happens If You Set Negative Mass?

Matter.js does not enforce strict input validation to block negative numbers when assigning mass. If you execute Body.setMass(body, -10), the engine will assign -10 to body.mass and -0.1 to body.inverseMass.

However, this corrupts collision resolution:

  1. Inverted Impulses: During a collision, the engine calculates a normal impulse to push overlapping bodies apart. Because the impulse formula multiplies the collision normal by a factor involving inverseMass, a negative sign inverts the vector. Instead of repelling each other, the bodies pull into each other.
  2. Exponential Acceleration: Because the bodies pull together instead of separating, penetration depth increases each frame. The solver attempts to correct this deeper overlap by applying an even larger inverted impulse, causing the bodies to violently accelerate toward one another.
  3. Simulation Crashes: Within a few frames, coordinate and velocity values exceed floating-point limits, turning into NaN (Not a Number) or Infinity. Once a body reaches NaN, it disappears from the canvas and corrupts any further calculations involving it.

Proper Alternatives for Antigravity and Buoyancy

If your goal is to create objects that float, push away from surfaces, or behave like theoretical "exotic matter," you should manipulate forces rather than applying negative mass.