DEV Community

Yang Hemmeter
Yang Hemmeter

Posted on

Implementing Fixed-Timestep Arcade Stunt Physics and Input Buffering in HTML5 Canvas (With FAQs)

When building 2D side-scrolling stunt, platformer, or vehicle physics games in HTML5 Canvas, relying directly on the frame delta from requestAnimationFrame is one of the fastest ways to introduce subtle, frustrating bugs. A jump arc or mid-air flip that feels crisp on a 60Hz laptop monitor can suddenly overshoot ledges, clip through slopes, or feel sluggish on a 120Hz or 144Hz display.

In this post, we will walk through a practical, lightweight architecture for deterministic fixed-timestep physics, render interpolation, and input buffering in vanilla JavaScript—followed by frequently asked questions from browser game development.

Why Variable Timesteps Break Arcade Physics

Most beginner loops multiply velocity and acceleration by dt (the elapsed time since the previous frame). While simple, variable dt causes three major issues in physics-driven arcade games:

  1. Integration Drift: Semi-implicit Euler integration produces slightly different trajectories depending on step size. A 16.6ms step and a 6.9ms step will not land on the exact same pixel after a 1.2-second airborne arc.
  2. Tunneling on Lag Spikes: If the browser pauses for garbage collection or a user switches tabs, dt can spike to 200ms or more. A fast-moving rider or projectile will teleport straight through thin collision surfaces.
  3. Inconsistent Feel Across Refresh Rates: High-refresh monitors poll physics more frequently, changing how friction, angular momentum, and torque accumulate unless every decay constant is rewritten using exponential scaling.

The Fixed-Timestep Accumulator Pattern

The standard solution is to decouple simulation updates from rendering. Physics always advances in fixed slices (for example, 1 / 120 seconds, or ~8.33ms), while Canvas renders as fast as the display refreshes using linear interpolation between the previous and current physics states.

Here is a compact, dependency-free implementation:

const FIXED_DT = 1 / 120; // 120 Hz deterministic simulation
const MAX_FRAME_TIME = 0.1; // Clamp spikes to prevent spiral of death

class ArcadeEngine {
  constructor() {
    this.accumulator = 0;
    this.lastTime = 0;

    this.prevState = { x: 0, y: 0, angle: 0 };
    this.currState = { x: 0, y: 0, angle: 0, vx: 0, vy: 0, omega: 0 };

    // Input buffering timers (in seconds)
    this.jumpBufferTimer = 0;
    this.coyoteTimer = 0;
    this.isGrounded = false;
  }

  queueJump() {
    this.jumpBufferTimer = 0.12; // 120ms input forgiveness window
  }

  stepPhysics(dt, input) {
    // Save snapshot for render interpolation
    this.prevState.x = this.currState.x;
    this.prevState.y = this.currState.y;
    this.prevState.angle = this.currState.angle;

    // Update forgiveness timers
    if (this.jumpBufferTimer > 0) this.jumpBufferTimer -= dt;
    this.coyoteTimer = this.isGrounded ? 0.08 : Math.max(0, this.coyoteTimer - dt);

    // Trigger jump if buffered input overlaps valid ground/coyote window
    if (this.jumpBufferTimer > 0 && this.coyoteTimer > 0) {
      this.currState.vy = -480;
      this.isGrounded = false;
      this.jumpBufferTimer = 0;
      this.coyoteTimer = 0;
    }

    // Apply gravity and rotational torque
    this.currState.vy += 1200 * dt;
    if (!this.isGrounded) {
      const torque = (input.leanRight ? 1 : 0) - (input.leanLeft ? 1 : 0);
      this.currState.omega += torque * 14 * dt;
      this.currState.omega *= Math.pow(0.25, dt); // Frame-rate safe damping
    }

    // Integrate positions
    this.currState.x += this.currState.vx * dt;
    this.currState.y += this.currState.vy * dt;
    this.currState.angle += this.currState.omega * dt;
  }

  render(ctx, alpha) {
    const drawX = this.prevState.x + (this.currState.x - this.prevState.x) * alpha;
    const drawY = this.prevState.y + (this.currState.y - this.prevState.y) * alpha;
    const drawAngle = this.prevState.angle + (this.currState.angle - this.prevState.angle) * alpha;

    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.save();
    ctx.translate(drawX, drawY);
    ctx.rotate(drawAngle);
    ctx.fillStyle = "#f97316";
    ctx.fillRect(-24, -12, 48, 24);
    ctx.restore();
  }

  tick(now, ctx, input) {
    if (!this.lastTime) this.lastTime = now;
    const frameTime = Math.min((now - this.lastTime) / 1000, MAX_FRAME_TIME);
    this.lastTime = now;
    this.accumulator += frameTime;

    while (this.accumulator >= FIXED_DT) {
      this.stepPhysics(FIXED_DT, input);
      this.accumulator -= FIXED_DT;
    }

    const alpha = this.accumulator / FIXED_DT;
    this.render(ctx, alpha);
  }
}
Enter fullscreen mode Exit fullscreen mode

Tuning Stunt Feel: Three Small Details That Matter

Once your simulation loop is deterministic, game feel comes down to forgiving edge cases rather than hyper-realistic equations:

  • Input Buffering (100ms–140ms): Players routinely press jump or boost a couple of frames before touching down on a ramp. Storing the intent in a countdown timer eliminates the perception of "dropped inputs."
  • Coyote Time (70ms–100ms): Allowing a jump right after wheels leave a ramp crest makes high-speed transitions feel responsive instead of punishing.
  • Landing Angle Tolerance: Instead of crashing a player the moment their chassis deviates by 20 degrees from a slope normal, define a forgiving suspension recovery zone (for example, up to 35 degrees off-normal) that snaps angular velocity smoothly back toward the terrain tangent.

Frequently Asked Questions (FAQs)

1. Should I run my fixed timestep at 60 Hz or 120 Hz?

If your game involves fast-moving bodies, narrow ramps, or stiff spring suspension, 120 Hz (1 / 120) significantly reduces tunneling and stabilizes spring-damper math while remaining inexpensive in modern JavaScript engines. For slower tile-based platformers, 60 Hz is usually sufficient.

2. Why do I need MAX_FRAME_TIME clamping?

When a browser tab goes into the background, requestAnimationFrame pauses. Returning to the tab can yield a frameTime of several seconds. Without clamping frameTime (typically to 0.1 seconds), the while loop would execute hundreds of catch-up physics steps in a single frame, freezing the main thread in what is known as the "spiral of death."

3. Does interpolation add noticeable input latency?

Render interpolation introduces at most one fixed physics step of visual delay. At 120 Hz, that is roughly 8.3 milliseconds—imperceptible to almost all players, and far preferable to the micro-stutter caused by uninterpolated 60 Hz logic running on a 144 Hz monitor.

4. How should I interpolate angles when a character does full 360-degree flips?

Avoid wrapping angle into [-PI, PI] inside the physics state before interpolating, otherwise linear interpolation will spin wildly backward across the wrap boundary. Keep continuous accumulated radians in prevState.angle and currState.angle during flips, or use shortest-arc angular interpolation only when resetting orientation.

Top comments (1)

Collapse
 
yuvaleizik profile image
Yuval Eizik •

the 120Hz vs 60Hz drift thing is real, i've had jump arcs feel totally different between my 240Hz and 155Hz monitors before switching to a fixed step. the input buffering part is a nice addition too, most tutorials skip it