What Is the Role of Sweep in Planck.js?

This article provides a comprehensive overview of the sweep property within the transform mathematics of Planck.js, a 2D physics engine for JavaScript. We will explore how the engine utilizes the sweep structure to track a body’s motion over time, handle continuous collision detection (CCD) to prevent fast-moving objects from passing through walls, and manage the interpolation of position and rotation between physics steps.


Understanding the Sweep Structure in Planck.js

Planck.js is a rewrite of the popular Box2D physics engine. In 2D rigid body dynamics, a body’s immediate position and orientation are typically represented by a transform matrix or a combination of a vector and a rotation angle. However, discrete time-stepping can fail when objects move at high velocities.

To solve this, Planck.js introduces the sweep property on rigid bodies. A sweep encodes the motion of a body’s center of mass over a specific time step. Instead of just knowing where an object is, the engine uses the sweep to know where the object started and where it is going during the current frame.

The sweep structure primarily contains the following components:


Continuous Collision Detection (CCD) and “Tunneling”

The most critical role of the sweep property is enabling Continuous Collision Detection (CCD) through a process called “Time of Impact” (TOI) calculation.

Without a sweep, a small, fast-moving bullet might be on one side of a thin wall in frame 1, and completely on the other side in frame 2. Because the discrete positions never overlap the wall, the engine misses the collision entirely. This bug is known as tunneling.

By using the sweep property, Planck.js can treat the motion of the body as a continuous trajectory from \((c0, a0)\) to \((c, a)\). The engine solves for the exact mathematical moment (\(alpha\)) between 0 and 1 when the shapes would first touch. If a collision is detected along the sweep path, the engine freezes the object at that specific fraction of the frame, processes the bounce or stop, and prevents it from passing through the obstacle.


Position Interpolation and the Transform

While the sweep property manages the underlying mathematical motion for the solver, rendering engines require a standard spatial transform (the actual \(x\), \(y\) coordinates and rotation angle) to draw the object on the screen.

Planck.js uses the sweep data to update the body’s primary transform. The engine interpolates between the start and end points of the sweep based on the elapsed time of the physics step:

\[\text{Position}(t) = (1 - \alpha) \cdot c_0 + \alpha \cdot c\]

This ensures that the collision geometry and the visual representation of the body remain perfectly synchronized, guaranteeing smooth movement and accurate physical behavior.