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);- When to use: Ideal for immediate UI reactions, teleportation, resetting a game state, or when you need strict, absolute control over an object’s rotation regardless of its physical mass.
- Unit of measurement: The velocity is measured in radians per second.
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:
- Body Type: Ensure your body type is set to
dynamic.staticbodies cannot rotate, andkinematicbodies will respond to direct velocity settings but will not react to torques or impulses. - Waking the Body: Physics engines put stationary bodies to “sleep” to save CPU cycles. If a body is sleeping, changing its velocity or applying forces might not have any effect until you wake it up.
// Force the body to wake up so it processes the velocity change
if (!body.isAwake()) {
body.setAwake(true);
}
body.setAngularVelocity(3.5);