Matter.js Default Coordinate System Explained
Matter.js uses a 2D screen-space coordinate system where the origin (0, 0) is situated at the top-left corner of the viewport or canvas. In this system, the horizontal X-axis increases from left to right, while the vertical Y-axis increases from top to bottom. This guide explains how this coordinate model functions, how body positions and rotations are calculated, and how it influences forces and gravity in your physics simulation.
The Origin and Axes
Unlike standard mathematical Cartesian coordinate systems where the Y-axis points upward, Matter.js follows the standard convention used by HTML5 Canvas and CSS screen coordinates:
- Origin (0, 0): Located at the top-left corner of the render context.
- X-Axis: Positive values move to the right, and negative values move to the left.
- Y-Axis: Positive values move downward, and negative values move upward.
Because positive Y increases downward, applying a positive vertical velocity or force moves a body toward the bottom of the screen.
Body Positioning and Center of Mass
When creating a rigid body in Matter.js (such as with
Bodies.rectangle(x, y, width, height)), the coordinates
(x, y) represent the body's center of
mass, not its top-left corner.
For example, creating a rectangle at x = 100,
y = 100 with a width = 50 and
height = 50 places the center point of the box at
(100, 100). Consequently:
- The left edge is at
x = 75 - The right edge is at
x = 125 - The top edge is at
y = 75 - The bottom edge is at
y = 125
If bounding box coordinates are needed, Matter.js calculates them
automatically under the body.bounds property
(min and max vertices).
Rotation and Angles
Matter.js measures angles in radians. Because the Y-axis is inverted relative to standard Cartesian coordinates, angular direction is oriented as follows:
- Positive angles: Rotate clockwise.
- Negative angles: Rotate counter-clockwise.
An angle of 0 radians points horizontally along the
positive X-axis (to the right). A rotation of Math.PI / 2
radians (90 degrees) turns the object toward the positive Y-axis
(pointing straight down).
Gravity and Directional Forces
Matter.js defines gravity along these same directional axes. By default, the engine's gravity is configured as:
engine.gravity.x = 0engine.gravity.y = 1engine.gravity.scale = 0.001
Because gravity.y is positive, objects naturally fall
toward the bottom of the screen. Inverting gravity to pull objects
upward requires setting engine.gravity.y to a negative
value.