How to Get Body Velocity in Matter.js
This guide explains how to retrieve both the linear and angular velocity of a physics body in Matter.js. You will learn how to read the velocity vector properties directly from a body instance, access scalar speed, and inspect these values in real-time during an active physics simulation loop.
Accessing Linear Velocity
In Matter.js, every rigid body automatically tracks its current
movement. You can retrieve a body's linear velocity by accessing its
velocity property, which returns a 2D vector containing
x and y components representing pixels per
engine update tick.
// Retrieve the full 2D velocity vector
const velocity = myBody.velocity;
// Access individual axes
const velocityX = myBody.velocity.x;
const velocityY = myBody.velocity.y;
console.log(`Velocity X: ${velocityX}, Velocity Y: ${velocityY}`);Retrieving Scalar Speed
If you need the magnitude of the velocity (the absolute speed without directional signs), Matter.js precalculates this value on the body:
// Returns the magnitude of the velocity vector
const currentSpeed = myBody.speed;
console.log(`Current Speed: ${currentSpeed}`);Accessing Angular Velocity
To determine how fast a body is rotating around its center of mass,
access the angularVelocity property, measured in radians
per tick:
const rotationalSpeed = myBody.angularVelocity;
console.log(`Angular Velocity: ${rotationalSpeed}`);Monitoring Velocity in the Simulation Loop
Because physics states change continuously, you should read the
velocity inside the update cycle. You can listen to engine events using
Matter.Events:
Matter.Events.on(engine, 'afterUpdate', () => {
const vx = myBody.velocity.x;
const vy = myBody.velocity.y;
// Perform actions based on current velocity
if (Math.abs(vx) > 5) {
console.log('Body is moving fast along the X-axis');
}
});Using afterUpdate ensures you are reading the final
velocity calculated for that specific frame after collisions and
constraints have been resolved.