How to Apply Continuous Force in Planck.js?

Planck.js is a 2D physics engine for JavaScript cross-compiled from Box2D, often used for games and simulations. Applying a continuous force to a body requires using the applyForce or applyForceToCenter methods inside the simulation’s update loop. This article covers the implementation steps, key code snippets, and the critical distinction between forces and impulses for continuous movement.

Understanding planck.js Forces

In planck.js, forces are meant to be applied gradually over time. Because the engine recalculates the physics world at every time step, a one-time force application will barely move an object. To create a continuous force—like gravity, wind, or a constant thruster—you must trigger the force method on every single frame.

The Implementation Steps

To keep a force active continuously, you need to hook into your game loop (typically driven by requestAnimationFrame) and apply the force before the world steps forward.

// 1. Define your world and a dynamic body
const world = planck.World();
const body = world.createBody({
  type: 'dynamic',
  position: planck.Vec2(0, 0)
});
body.createFixture(planck.Box(1, 1));

// 2. Define the force vector (X and Y components)
const forceAmount = planck.Vec2(10.0, 0.0); // Pushes to the right

// 3. The continuous simulation loop
function update() {
  // Apply the force every frame to make it continuous
  body.applyForceToCenter(forceAmount, true);

  // Step the world forward (e.g., 1/60th of a second)
  world.step(1 / 60);

  requestAnimationFrame(update);
}

requestAnimationFrame(update);

Choosing the Right Method

There are two primary methods for applying force depending on whether you want to induce rotation:

The wake parameter (a boolean) should generally be set to true to ensure that if the body has gone to “sleep” from inactivity, the new force wakes it up to resume physics calculations.

Force vs. Impulse

When writing continuous movement logic, ensure you are not using applyLinearImpulse. Impulses model immediate, instantaneous changes in momentum (like a bat hitting a baseball). If applied every frame, an impulse will cause uncontrollable, exponential acceleration. Forces are automatically multiplied by the time step (\(F = ma\)), making them the correct choice for smooth, continuous acceleration.