How Matter.js Simulates Default Gravity

Matter.js is a lightweight 2D rigid body physics engine for the web that includes a built-in gravity system to mimic real-world physics right out of the box. By default, Matter.js applies a constant downward acceleration to all dynamic bodies within a world simulation. This article breaks down how the default gravity properties are structured, how the engine calculates gravitational forces on each tick, and how it ensures objects fall naturally regardless of their mass.

The Default Gravity Properties

In Matter.js, gravity is configured globally at the engine level through the engine.gravity object. When an engine instance is initialized without custom parameters, Matter.js assigns the following default properties:

Together, these values define a vector (0, 1) that exerts a steady downward acceleration.

Force Calculation and Mass Independence

Matter.js updates its simulation using discrete time steps, typically tied to the browser's refresh rate. During each Engine.update cycle, the engine calculates the gravitational force to apply to each body.

The applied gravitational force vector is determined by:

force.x = body.mass * gravity.x * gravity.scale
force.y = body.mass * gravity.y * gravity.scale

Because Newton's second law dictates that acceleration equals force divided by mass (\(a = F / m\)), dividing the gravitational force by the body's mass cancels the mass variable out of the acceleration equation. As a result, all dynamic bodies experience the exact same rate of acceleration regardless of their size, density, or mass—faithfully reproducing Galilean gravity in a vacuum.

Interaction with Body Types

Gravity does not affect all bodies equally in Matter.js:

Adjusting or Disabling Gravity

Because default gravity is stored directly on the engine instance, it can be altered in real-time. Setting engine.gravity.y = 0 creates a zero-gravity environment, negative values invert the direction so objects float upward, and modifying engine.gravity.x introduces directional drift, such as horizontal wind.