How to Set the Initial Angle in Matter.js

This guide explains how to set the initial rotation angle of a rigid body in the Matter.js 2D physics engine. You will learn how to configure the angle upon body instantiation using configuration options, how to modify it programmatically after creation using the Matter.Body module, and how to properly convert degrees to radians, which Matter.js requires for all angular measurements.

1. Set the Angle at Instantiation

The most direct way to set an initial angle is by passing the angle property within the options parameter when creating a body with factory methods like Bodies.rectangle or Bodies.circle.

Matter.js expects angles to be measured in radians, not degrees.

const { Bodies } = Matter;

// 45 degrees in radians
const initialAngle = Math.PI / 4; 

const box = Bodies.rectangle(400, 200, 80, 80, {
    angle: initialAngle
});

2. Set the Angle After Instantiation

If the body has already been created, set its angle before starting the physics simulation by calling Body.setAngle(). This updates the body's rotation, its vertices, and its internal inertia matrices properly.

const { Bodies, Body } = Matter;

const box = Bodies.rectangle(400, 200, 80, 80);

// Set the angle immediately after creation
Body.setAngle(box, Math.PI / 2); // Rotated 90 degrees

Do not modify box.angle = Math.PI / 2 directly, as this bypasses the recalculation of collision bounds and vertex positions. Always use Body.setAngle(body, angle).

Converting Degrees to Radians

Because standard web development often references degrees (0° to 360°), use the standard conversion formula when defining initial angles:

\[\text{radians} = \text{degrees} \times \left(\frac{\pi}{180}\right)\]

In JavaScript:

function degreesToRadians(degrees) {
    return degrees * (Math.PI / 180);
}

const rotatedBody = Bodies.rectangle(300, 150, 100, 50, {
    angle: degreesToRadians(30) // Set initial tilt to 30 degrees
});