What happens to planck.js position vectors with NaN?

Feeding NaN (Not-a-Number) values into a planck.js position vector breaks the underlying physics simulation, causing computational failures, invisible or disappearing bodies, and cascading errors across the physics world. This article explores how planck.js handles NaN inputs, why it leads to silent failures, and how you can prevent it from ruining your 2D physics simulations.

How planck.js Reacts to NaN Values

Planck.js is a JavaScript port of the Box2D physics engine. It relies heavily on continuous mathematical calculations for linear algebra, collision detection, and constraint solving. When a NaN value is introduced into a position vector (such as Vec2(NaN, 5) or via body.setPosition()), the engine does not typically throw an immediate runtime error. Instead, it fails silently and propagates through the system.

Common Causes of NaN in Physics Vectors

NaN values rarely appear out of nowhere; they are usually the result of upstream coding logic flaws before the data is passed to planck.js.

How to Prevent and Debug NaN Errors

Because planck.js fails silently, debugging NaN issues can be incredibly frustrating. The best defense is proactive validation.

function createSafeVec2(x, y) {
    if (Number.isNaN(x) || Number.isNaN(y)) {
        console.error("Warning: NaN detected in vector initialization!");
        return planck.Vec2(0, 0); // Safe fallback
    }
    return planck.Vec2(x, y);
}