How to Lock Rotation of a Body in Matter.js

Locking the rotation of a body in Matter.js prevents it from tumbling or turning upon collision, which is essential for character controllers, moving platforms, and sliding objects. This guide demonstrates the standard and most reliable methods to freeze a body's rotation while still allowing it to move along the X and Y axes, primarily by utilizing infinite inertia.

Method 1: Set Inertia to Infinity at Creation

The cleanest way to disable rotation is to define the body's inertia property as Infinity when you instantiate it. In physics simulations, infinite inertia means no amount of torque can cause the body to rotate.

const { Bodies } = Matter;

// Create a body with locked rotation
const player = Bodies.rectangle(400, 200, 50, 100, {
    inertia: Infinity
});

Because inertia is set to Infinity, the body can be pushed, pulled by gravity, and collide with other objects, but its angle will never change.

Method 2: Lock Rotation Dynamically Using Body.setInertia

If the body has already been created, or if you need to toggle rotation locking during runtime, use the Body.setInertia utility function.

const { Body } = Matter;

// Lock rotation
Body.setInertia(player, Infinity);

If you ever need to restore default rotation behavior, you can recalculate and restore the body's natural inertia using its mass and geometry, or reassign a calculated value:

// Re-enable rotation by calculating standard inertia for a rectangle
const defaultInertia = (player.mass * (player.width ** 2 + player.height ** 2)) / 12;
Body.setInertia(player, defaultInertia);

Resetting Existing Rotation

If a body has already rotated before you set its inertia to Infinity, it will remain stuck at that specific rotated angle. To make sure the body is upright when locked, manually reset its angle and angular velocity:

Body.setAngle(player, 0);
Body.setAngularVelocity(player, 0);
Body.setInertia(player, Infinity);

Difference Between inertia: Infinity and isStatic: true

Setting isStatic: true locks both rotation and translation, meaning the body cannot move at all. Setting inertia: Infinity only locks the rotation, leaving linear velocity, forces, and collisions along the X and Y planes completely functional.