How to Stop planck.js Body Rotation?
In planck.js (the JavaScript port of the Box2D physics engine), you often need a rigid body that can move freely in the 2D plane but must remain perfectly upright or oriented in a fixed direction. This article provides a quick overview of how to lock a body’s rotation, detailing the most efficient property-based method, alternative joint-based workarounds, and how to dynamically toggle this behavior during gameplay.
The Best Method: Using
fixedRotation
The cleanest and most computationally efficient way to prevent a
planck.js body from rotating is by setting its fixed
rotation flag to true. This instructs the physics
solver to completely ignore any rotational forces (torques) acting on
the body while leaving its linear velocity and forces unaffected.
Setting Fixed Rotation During Initialization
When creating your physics body, you can pass
fixedRotation: true directly inside the body definition
object.
const body = world.createBody({
type: 'dynamic',
position: planck.Vec2(0, 5),
fixedRotation: true // Prevents any rotation from the start
});Setting Fixed Rotation Post-Creation
If you need to change this behavior after the body has already been instantiated, planck.js provides a built-in setter method.
// Lock the rotation later in your code
body.setFixedRotation(true);
// Unlock the rotation to allow the body to spin again
body.setFixedRotation(false);Alternative Method: Using a Prismatic Joint
While fixedRotation is almost always the preferred
solution, specialized game mechanics might require you to restrict
rotation relative to another moving body rather than the world axis. In
these rare scenarios, you can use a Prismatic
Joint.
A Prismatic Joint restricts the relative motion of two bodies along a specified axis and completely prevents relative rotation between them.
const jointDef = {
anchorA: bodyA.getWorldCenter(),
localAxisA: planck.Vec2(1, 0), // Allows movement along this axis
enableLimit: false
};
world.createJoint(planck.PrismaticJoint(jointDef, bodyA, bodyB));Common Pitfalls to Avoid
- Manually Resetting Angle to Zero: Avoid resetting
body.setAngle(0)inside your game’s update loop. Forcing the angle manually conflicts with the internal physics solver, causing jittery collisions and unexpected visual glitches. - Overlooking Mass Properties: When you enable
fixedRotation, planck.js automatically manages the body’s rotational inertia (\(I\)). Manually overriding the mass data right after setting fixed rotation can sometimes conflict with the flag, so always set your fixed rotation property last.