logo
By Lawrence

5 minutes

Draw the Shot First

The gold curve only works with one planet. Add a second mass and the formula breaks. The step doesn't care how many masses there are. So to predict a shot, we fly a ghost ball ahead of time with the same step.

The fixed step

Frames don't all take the same time. If the game stepped once per frame, a fast computer and a slow one would fly different paths. So the game never steps by the frame's time. It spends each frame's time in whole steps of 1/120 s, and carries what's left over into the next frame:

Three frames of 20 ms each above, and below them the 8.33 ms steps each frame pays for. Frames 1 and 2 buy two steps each, frame 3 buys three, and a sliver is left over for the next frame.

src/components/GravityBody/GravityBody.core.ts
/**
 * Spend `dt` seconds of frame time in whole fixed steps. Returns how many to
 * take and the time left over for next frame. The backlog beyond `maxSteps` is
 * DROPPED, not carried — carrying it would only make the next frame worse.
 */
export function planSteps(
  carried: number,
  dt: number,
  step: number = GRAVITY_STEP,
  maxSteps: number = MAX_STEPS_PER_FRAME,
): { steps: number; carry: number } {
  const total = carried + Math.max(0, dt);
  const steps = Math.floor(total / step);
  if (steps > maxSteps) return { steps: maxSteps, carry: 0 };
  return { steps, carry: total - steps * step };
}
planSteps(0, 1 / 60)  // { steps: 2, carry: 0 }
planSteps(0, 1 / 50)  // { steps: 2, carry: 0.003333 }   the leftover waits for the next frame
planSteps(0, 10)      // { steps: 12, carry: 0 }         a 10 s freeze takes 12 and drops the rest

So the balls take the same steps on a slow screen and a fast one. A ghost flown with the same step does the same sums, and lands in the same place.

Continue reading

Unlock the Full Course

Every lesson, the runnable examples, and the finished build — yours to keep.

$9one-time

Was this page helpful?

We read every note — tell us what's working and what isn't.

↑↓ NavigateEnter SelectEsc CloseCtrl+K Open Search