How to Apply Linear Impulse to Center of Mass in Planck.js?
Applying a linear impulse directly to the center of mass of a
planck.js body changes its linear velocity without inducing
any angular rotation (torque). This article provides a quick overview of
how to calculate a body’s center of mass, invoke the proper
applyLinearImpulse method, and avoid unintended rotational
forces in your 2D physics simulations.
Understanding the Method
In planck.js (a JavaScript port of the Box2D physics
engine), the Body object provides a built-in method called
applyLinearImpulse. To apply an impulse specifically to the
center of mass, you must pass the impulse vector and the body’s current
world center position as arguments.
The method signature generally looks like this:
body.applyLinearImpulse(impulse, point, wake);impulse: AVec2object representing the direction and magnitude of the force applied over time (in Newton-seconds).point: AVec2object representing the world coordinates where the impulse is applied. To avoid rotation, this must be the center of mass.wake: A boolean (usuallytrue) indicating whether to wake up the body if it is currently sleeping.
Step-by-Step Implementation
1. Get the Center of Mass
You can retrieve the precise world coordinates of a body’s center of
mass using the getWorldCenter() method. This ensures that
even if the body has moved or rotated, you are targeting the exact point
of balance.
const centerOfMass = body.getWorldCenter();2. Define the Impulse Vector
Create a 2D vector that defines how much force you want to apply and in what direction.
const Vec2 = planck.Vec2;
const impulse = Vec2(10.0, 0.0); // Applies a force of 10 units to the right3. Apply the Impulse
Pass both the impulse vector and the center of mass vector into the method.
body.applyLinearImpulse(impulse, centerOfMass, true);Why the Application Point Matters
When an impulse is applied to any point other than the center of
mass, it creates a turning moment (torque) based on the distance between
the application point and the center of mass. By explicitly passing
body.getWorldCenter() as the application point, the lever
arm length is effectively zero. This guarantees that the object will
move in a straight line according to the impulse vector without
spinning.