How to Convert World to Local Vector in Planck.js?

Converting a world space vector to a body’s local space vector is a common task in 2D physics engines like Planck.js (a JavaScript rewrite of Box2D). This article provides a straightforward guide on how to perform this coordinate transformation using Planck.js’s built-in body methods. You will learn the specific API functions to use, see a practical code example, and understand why this conversion is essential for handling local forces and offsets.

Understanding World vs. Local Coordinates

In Planck.js, the physics simulation operates on a global coordinate system known as World Space. Every object’s absolute position and velocity are tracked here. However, when you want to apply a force relative to an object’s current orientation—such as a thruster on the back of a rotating spaceship—you need to work in Local Space.

Using the getLocalVector Method

Planck.js provides a built-in method on the Body class specifically designed for this transformation: Body.getLocalVector(worldVector).

This method takes a vector defined in world coordinates and transforms it into the local coordinate system of that specific body, accounting for the body’s current rotation.

Code Example

Here is how you can implement this in your project:

import { Vec2, World } from 'planck';

// 1. Initialize world and a rigid body
const world = new World();
const body = world.createBody({
  type: 'dynamic',
  position: Vec2(5, 10),
  angle: Math.PI / 4 // Rotated 45 degrees
});

// 2. Define a vector in world space (e.g., pointing straight up)
const worldVector = Vec2(0, 1);

// 3. Convert the world vector to the body's local space
const localVector = body.getLocalVector(worldVector);

console.log(`Local Vector: x=${localVector.x}, y=${localVector.y}`);

Local Vector vs. Local Point

It is important to distinguish between transforming a vector (direction and magnitude) and a point (an absolute location):