How to Apply Torque to a Body in Matter.js

In Matter.js, applying torque to rotate a rigid body can be achieved either by directly modifying the body's torque property or by applying an off-center force using the Matter.Body.applyForce() method. This article covers both techniques, explaining how to implement them within the engine's update loop and when to use direct angular velocity adjustments for immediate rotational changes.

Method 1: Directly Modifying the torque Property

The most straightforward way to add rotational force is by setting or incrementing the torque property on the target body. Matter.js resets this value to zero at the end of every physics step, so the torque must be applied continuously within the engine loop.

// Register an event listener before the physics update runs
Matter.Events.on(engine, 'beforeUpdate', function() {
    // Add a positive value for clockwise, negative for counter-clockwise
    myBody.torque = 0.05; 
});

Because torque = inertia * angularAcceleration, a body with high inertia (often determined by its mass, width, and height) requires a larger torque value to achieve visible acceleration.

Method 2: Applying an Off-Center Force

In real-world physics, torque is generated when a force is applied at a distance from the center of mass (\(\tau = r \times F\)). In Matter.js, you can replicate this using Matter.Body.applyForce(). If the point of application is offset from body.position, the engine automatically computes both the linear force and the resulting torque.

// Define a point offset from the center of mass
const applicationPoint = {
    x: myBody.position.x + 20, // 20 units to the right of center
    y: myBody.position.y
};

// Define the directional force vector
const force = {
    x: 0,
    y: -0.01 // Upward force
};

// Apply the force
Matter.Body.applyForce(myBody, applicationPoint, force);

Applying force above or below the center of mass in a horizontal direction, or to the left or right in a vertical direction, causes the body to spin while simultaneously pushing it linearly.

Alternative: Setting Angular Velocity Directly

If you need an instantaneous change in rotation without relying on force accumulation or mass properties, you can directly set the angular velocity using Matter.Body.setAngularVelocity().

// Set rotational speed directly (in radians per step)
Matter.Body.setAngularVelocity(myBody, 0.1);

This bypasses torque and inertia calculations entirely, instantly making the body spin at the specified rate. Use direct torque or off-center forces when realistic physical acceleration is required, and use angular velocity when you need immediate, deterministic rotation.