How to Get Angular Velocity in Matter.js
In Matter.js, retrieving a rigid body's current rotational speed is
handled directly through the body's internal properties. This guide
demonstrates how to read the angularVelocity property on
any simulated physics body, explains the measurement units used by the
engine, and shows how to monitor changes to rotational speed in real
time during the physics simulation loop.
Reading the
angularVelocity Property
Every rigid body created using the Matter.Bodies factory
or the Matter.Body.create method contains an
angularVelocity property. You can read this value directly
from the body instance at any point during your simulation.
// Assuming 'box' is an existing Matter.js body
const currentAngularVelocity = box.angularVelocity;
console.log(`Current Angular Velocity: ${currentAngularVelocity}`);Understanding the Units
Matter.js measures angularVelocity in radians
per step (or update tick, which typically defaults to
approximately 16.67ms or 60 frames per second):
- Positive value: The body is rotating clockwise.
- Negative value: The body is rotating counter-clockwise.
- Zero: The body is not currently rotating.
To convert this value to degrees per frame, you can multiply the
value by 180 / Math.PI:
const degreesPerFrame = box.angularVelocity * (180 / Math.PI);Monitoring Angular Velocity in Real Time
Because physics interactions change a body's velocity constantly, you
typically want to read angularVelocity inside the engine's
update cycle. You can hook into the engine's events using
Matter.Events:
const { Engine, Events, Bodies, World } = Matter;
const engine = Engine.create();
const box = Bodies.rectangle(400, 200, 80, 80);
World.add(engine.world, [box]);
// Listen to the 'afterUpdate' event to read velocity each frame
Events.on(engine, 'afterUpdate', () => {
const angularVelocity = box.angularVelocity;
// Check if the body is actively spinning
if (Math.abs(angularVelocity) > 0.001) {
console.log(`Angular Velocity: ${angularVelocity.toFixed(4)} rad/step`);
}
});Difference Between Reading and Setting
While reading the current angular velocity requires only accessing
body.angularVelocity, setting or modifying it directly
should be done using the built-in helper method to maintain accurate
physics calculations across frames:
// Setting angular velocity
Matter.Body.setAngularVelocity(box, 0.15);
// Reading angular velocity
const currentSpin = box.angularVelocity;