How to Set Absolute Position of a Body in Matter.js

Moving a rigid body to an exact coordinate in Matter.js requires safely updating its internal state without breaking the physics engine's collision calculations. This guide covers how to set a body's absolute position using the Matter.Body.setPosition method, why you should avoid directly mutating the position vector, and how to reset velocities to prevent unwanted physics artifacts during teleportation.

Using Body.setPosition

The official and correct way to move a body to an absolute coordinate is using the Body.setPosition utility function provided by the Matter.Body module.

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

// Define your target coordinates
const newPosition = { x: 400, y: 300 };

// Update the body's absolute position
Body.setPosition(myBody, newPosition);

Why You Should Not Mutate body.position Directly

It can be tempting to assign coordinates directly using myBody.position.x = 400, but this can introduce bugs into the simulation.

When you call Body.setPosition(), Matter.js updates the position vector while simultaneously updating the body's vertices, bounding box (AABB), and internal broadphase collision data. Mutating myBody.position directly skips these recalculations, leading to "ghost collisions" where the physical collider remains at the old position while the visual coordinates move.

Resetting Velocity When Teleporting

If you reposition a body that already has active motion, its linear and angular momentum will persist. If you want to instantly teleport a body and stop it from continuing in its previous trajectory, you should zero out its velocity and angular velocity immediately after repositioning it:

// Teleport the body
Body.setPosition(myBody, { x: 400, y: 300 });

// Clear momentum to prevent the body from flying away
Body.setVelocity(myBody, { x: 0, y: 0 });
Body.setAngularVelocity(myBody, 0);

Repositioning Dynamic vs. Static Bodies