How to Change Angular Velocity in Planck.js?

Planck.js is a 2D physics engine for JavaScript applications, refactored from Box2D for cross-platform optimization. To change the angular velocity of a rigid body within this engine, developers can directly manipulate the body’s properties using the setAngularVelocity() method, or apply rotational forces over time using torques and impulses. This article provides a straightforward guide on how to implement these methods, choose the right approach for your physics simulation, and troubleshoot common pitfalls like sleeping bodies.

Direct Modification: setAngularVelocity()

The most direct way to alter how fast a body rotates is by explicitly setting its angular velocity. This method overrides any current rotational momentum and immediately forces the body to spin at the specified rate.

// Set the angular velocity to 2 radians per second clockwise/counter-clockwise depending on your setup
body.setAngularVelocity(2.0);

Physical Force: applyTorque() and applyAngularImpulse()

If you want a more realistic simulation where objects take time to speed up or slow down based on their mass and inertia, you should apply forces instead of setting the velocity directly.

1. Applying Continuous Torque

Torque is a rotational force applied over time. Calling this inside your simulation loop will gradually accelerate or decelerate the body’s spinning speed.

// Apply a rotational force to the body
body.applyTorque(15.0);

2. Applying an Angular Impulse

An impulse is an instantaneous force. Think of it like hitting a spinning top with your finger—it applies an immediate change in velocity that accounts for the body’s mass.

// Apply an instant rotational burst
body.applyAngularImpulse(5.0);

Important Technical Considerations

When modifying a body’s velocity programmatically, keep the following Box2D/Planck.js mechanics in mind to avoid unexpected behavior:

// Force the body to wake up so it processes the velocity change
if (!body.isAwake()) {
  body.setAwake(true);
}
body.setAngularVelocity(3.5);