How to Convert Local to World Point in Planck.js?
This article provides a straightforward guide on how to convert a
local coordinate point within a rigid body to a global world coordinate
point using the planck.js 2D physics engine. You will learn
about the specific utility methods available on the Body
prototype, see a practical code example, and understand the core
differences between local and world spaces.
Understanding Local vs. World Space
In planck.js (a JavaScript rewrite of Box2D), physics
simulations manage two main coordinate systems:
- World Space: The global coordinate system of the entire physics world. The position of every body is tracked relative to this global origin \((0, 0)\).
- Local Space: A coordinate system local to a specific rigid body. The origin \((0, 0)\) of local space is always the center of the body itself. Shape fixtures, like polygons or circles, are defined using local coordinates.
Converting from local space to world space is essential when you need to know where a specific point on a moving or rotating object is actually located within the broader game or simulation world.
Using the
getWorldPoint Method
The Body object in planck.js provides a
built-in utility method specifically for this transformation:
Body.getWorldPoint(localPoint).
Syntax
body.getWorldPoint(localPoint);localPoint: AVec2object representing the coordinates relative to the body’s center.- Returns: A new
Vec2object representing the absolute coordinates in the world.
Code Example
Below is a practical implementation showing how to set up a body and compute its world point.
import planck from 'planck-js';
// 1. Initialize world and a rigid body
const world = planck.World();
const body = world.createBody({
type: 'dynamic',
position: planck.Vec2(5.0, 10.0), // Body is at (5, 10) in the world
angle: Math.PI / 4 // Rotated 45 degrees
});
// 2. Define a local point (e.g., an offset of 2 units on the local X-axis)
const localPoint = planck.Vec2(2.0, 0.0);
// 3. Convert the local point to a world point
const worldPoint = body.getWorldPoint(localPoint);
console.log(`World X: ${worldPoint.x}, World Y: ${worldPoint.y}`);Alternative Method:
getWorldVector
If you only need to transform a directional vector (like a force or
velocity) rather than an exact spatial position, use
body.getWorldVector(localVector).
Unlike getWorldPoint, getWorldVector only
applies the body’s rotation to the vector, completely
ignoring the body’s physical position translation. This is useful for
projecting local forces into global directions.