How to Change Moment of Inertia in Matter.js

This article explains how to modify the moment of inertia for rigid bodies in the Matter.js 2D physics engine. You will learn what inertia controls in Matter.js, how to configure it during initial body instantiation, and how to update it dynamically during runtime using built-in engine methods, including how to lock rotation entirely by using infinite inertia.

Understanding Inertia in Matter.js

In Matter.js, the moment of inertia represents a rigid body's resistance to rotational acceleration when torque is applied. By default, Matter.js calculates this value automatically based on the body's mass and geometric dimensions. Lower values allow an object to spin freely with minimal torque, while higher values make an object harder to rotate.

Setting Inertia During Body Creation

You can define a custom moment of inertia directly in the options object when instantiating a new body using the Matter.Bodies factory methods.

// Create a rectangle with a custom inertia value
const box = Matter.Bodies.rectangle(400, 200, 80, 80, {
    mass: 5,
    inertia: 5000 // Custom moment of inertia
});

Matter.Composite.add(engine.world, box);

When you define inertia at creation, Matter.js also computes the corresponding inverseInertia property (1 / inertia), which the physics engine uses internally during collision and constraint solving.

Changing Inertia Dynamically at Runtime

If a body has already been created, you should never mutate body.inertia directly. Direct mutation leaves internal engine properties—such as inverseInertia—out of sync, leading to physics calculation errors.

Instead, use the Matter.Body.setInertia utility method:

// Import the Body module
const { Body } = Matter;

// Dynamically update the body's moment of inertia
Body.setInertia(box, 12000);

Calling Body.setInertia() recalculates both body.inertia and body.inverseInertia safely.

Preventing Rotation Entirely

To make an object immune to rotational forces (such as for a player character that should stay upright without tipping), set the inertia to Infinity:

// During creation
const player = Matter.Bodies.rectangle(100, 100, 40, 80, {
    inertia: Infinity
});

// Or dynamically at runtime
Matter.Body.setInertia(player, Infinity);

Alternatively, Matter.js provides a shorthand method for setting infinite inertia:

Matter.Body.setStatic(body, false); // Keep dynamic translation
Matter.Body.setInertia(body, Infinity); // Prevents rotation

Setting inertia: Infinity changes inverseInertia to 0, effectively stopping any angular acceleration regardless of collision impacts or applied torque.