How to Rotate a Body in Matter.js

This guide explains how to programmatically rotate physics bodies in Matter.js using built-in engine methods. You will learn how to set an explicit orientation, apply relative incremental rotation, and drive continuous rotation using angular velocity, alongside critical considerations like radian conversion and physics body types.

1. Absolute Rotation: Body.setAngle

To snap or set a body to a specific orientation, use Matter.Body.setAngle(). This method overrides the body's current rotation and immediately sets it to the specified angle in radians.

const { Body } = Matter;

// Rotate the body to a 45-degree angle
const angleInRadians = Math.PI / 4; 
Body.setAngle(myBody, angleInRadians);

2. Relative Rotation: Body.rotate

To turn a body by a specific amount relative to its current rotation, use Matter.Body.rotate(). This adds the specified angle to the body's existing angle.

const { Body } = Matter;

// Rotate the body an additional 0.05 radians
Body.rotate(myBody, 0.05);

// You can also rotate around an arbitrary pivot point:
const pivotPoint = { x: 100, y: 100 };
Body.rotate(myBody, 0.05, pivotPoint);

3. Continuous Rotation: Body.setAngularVelocity

If you want the physics engine to rotate the body smoothly over time based on physical motion, set its angular velocity using Matter.Body.setAngularVelocity().

const { Body } = Matter;

// Apply a constant rotational speed
Body.setAngularVelocity(myBody, 0.1);

Important Considerations