How to Convert Radians to Degrees in Planck.js?

Planck.js, a 2D physics engine for JavaScript, calculates all angular rotations, velocities, and angles exclusively in radians. This article provides a quick overview of why Planck.js uses radians, demonstrates the mathematical formula required to convert those values into degrees, and offers practical code examples for updating your rendering engine or user interface.


Why Planck.js Uses Radians

Like Box2D (the engine it is ported from), Planck.js relies on radians because they simplify the internal trigonometric calculations required for rigid body physics simulation. However, most web rendering frameworks, UI components, and human developers inherently think in degrees, where a full circle is \(360^\circ\) instead of \(2\pi\) radians.

To bridge this gap, you must convert the body’s rotation angle whenever you pull data out of the physics world to draw it on the screen.


The Conversion Formula

To convert radians to degrees, you multiply the radian value by \(180\) and divide it by Pi (\(\pi\)).

\[\text{Degrees} = \text{Radians} \times \left(\frac{180}{\pi}\right)\]

In JavaScript, this math translates directly to using Math.PI.


Implementing the Conversion in JavaScript

You can write a simple helper function or perform the inline calculation when fetching the angle from a Planck.js body.

Step-by-Step Code Example

// 1. Get the angle in radians from the Planck.js body
const radians = body.getAngle();

// 2. Convert radians to degrees
const degrees = radians * (180 / Math.PI);

// 3. Apply to your visual asset (e.g., in PixiJS, Three.js, or HTML5 Canvas)
myVisualSprite.angle = degrees;

Creating a Reusable Helper

For cleaner architecture, isolate the math into a utility function that can be utilized throughout your game loop:

function radToDeg(radians) {
    return radians * (180 / Math.PI);
}

// Usage in your game tick/render loop
function update() {
    world.step(1 / 60);
    
    const playerAngleRad = playerBody.getAngle();
    const playerAngleDeg = radToDeg(playerAngleRad);
    
    renderPlayer(playerAngleDeg);
}

Common Pitfalls to Avoid