How to Move a Body Relative to Its Position in Matter.js

Moving a physics body relative to its current position in Matter.js is a fundamental task for handling character controls, dynamic obstacles, and interactive animations. This article demonstrates the most effective methods to achieve relative translation using Matter.js's built-in vector and body modules, highlights the difference between direct position shifting and physics-based movement, and provides concise code examples to implement this in your project.

Using Matter.Body.translate

The simplest and most direct way to move a body relative to where it currently sits is using the Matter.Body.translate function. This method automatically updates the body's position, vertices, and bounding box by adding a translation vector to its existing coordinates.

// Move the body 10 units to the right and 5 units up
Matter.Body.translate(myBody, { x: 10, y: -5 });

Matter.Body.translate takes two arguments:

  1. body: The target Matter.Body instance you want to manipulate.
  2. translation: An object specifying { x, y } delta offsets to apply.

Using Matter.Body.setPosition with Current Coordinates

Alternatively, you can achieve the exact same behavior by manually reading the body's current position and passing the calculated offset into Matter.Body.setPosition.

Matter.Body.setPosition(myBody, {
  x: myBody.position.x + 10,
  y: myBody.position.y - 5
});

While functional, Matter.Body.translate is preferred because it is specifically designed for delta-based displacement and keeps your code cleaner.

Translating Static vs. Dynamic Bodies

When changing the position of a body relatively, consider its body type:

Moving Relatively Using Velocity

If you want a dynamic body to move relative to its current direction while preserving physics interactions (such as pushing objects or respecting mass), adjust its velocity instead of directly overriding coordinates:

// Apply an immediate relative change to horizontal speed
Matter.Body.setVelocity(myBody, {
  x: myBody.velocity.x + 5,
  y: myBody.velocity.y
});

For continuous, force-driven movement where the body accelerates smoothly, use Matter.Body.applyForce instead.