How do you code air resistance?
Add a drag term proportional to v² to a falling object and it reaches a terminal velocity. Code it in a few lines of JavaScript and check it against the exact solution.
How do you code air resistance?
Add one term to the acceleration: gravity pulls down at , and drag pushes back with , where . Step the speed forward with and the object speeds up, then levels off at the terminal velocity — exactly what happens in a real fall.
This is the code companion to How free fall works, which derives the drag force and terminal velocity.
The whole simulation
const g = 9.81, rho = 1.225; // m/s², kg/m³
const m = 80, CdA = 0.7; // skydiver: mass (kg), drag coefficient × area (m²)
const k = (0.5 * rho * CdA) / m; // drag acceleration per v²
const vTerminal = Math.sqrt(g / k); // 42.8 m/s
// s.v = downward speed (m/s), s.y = distance fallen (m)
function step(s, dt) {
const a = g - k * s.v * s.v; // gravity minus quadratic drag
s.v += a * dt; // update velocity first…
s.y += s.v * dt; // …then position with the new velocity
}
// Closed-form solution for quadratic drag, used as the test oracle
const exact = (t) => ({
v: vTerminal * Math.tanh((g * t) / vTerminal),
y: ((vTerminal * vTerminal) / g) * Math.log(Math.cosh((g * t) / vTerminal)),
});
const s = { v: 0, y: 0 };
for (let t = 0; t < 30; t += 0.01) step(s, 0.01);
console.log(s, exact(30));Does it match the exact solution?
For this skydiver the terminal velocity is m/s, reached to within 5% after s and within 1% after s. Compared with a drag-free fall ( m/s after s), drag has already held the speed to m/s. Distance fallen in s:
| Time step | Distance fallen in 30 s | Error vs exact |
|---|---|---|
| 0.1 s | 1157.6 m | +0.3% |
| 0.01 s | 1154.5 m | +0.03% |
| 0.001 s | 1154.2 m | ≈ 0 |
| exact | 1154.2 m | — |
Going to two dimensions with wind
In 2D, drag opposes the motion relative to the air. If the air moves with velocity , use and apply to both components. A tailwind then reduces drag on the ball; a headwind increases it. The Ball Gravity simulation keeps things simpler: wind is just a constant horizontal acceleration, with no drag.
Frequently asked questions
How do I calculate terminal velocity in code?
Why does my falling object oscillate or blow up?
What values of Cd and area should I use?
Do I need the mass?
Keep exploring
- The physics first: How does free fall work?.
- Choosing integrators and measuring their error: Simulating a pendulum in code.
- Try wind and gravity: Ball Gravity simulation.