Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

Engineering 60FPS 16-Ball Billiards Physics, Cushion Restitution & 1v1 Sync in HTML5 Canvas (8 Ball Pool Online)

Engineering 60FPS 16-Ball Billiards Physics, Cushion Restitution & 1v1 Sync in HTML5 Canvas Building a responsive browser billiards game sounds straightforward until a full-power break shot slams the cue ball into a ti

Engineering 60FPS 16-Ball Billiards Physics, Cushion Restitution & 1v1 Sync in HTML5 Canvas

Building a responsive browser billiards game sounds straightforward until a full-power break shot slams the cue ball into a tightly packed 15-ball triangle. At 60 FPS (16.67ms per frame), a fast cue ball moving 28+ pixels per frame will tunnel straight through neighboring balls, clip into corner pockets, or get wedged in overlapping rack geometry unless your collision solver uses sub-stepping and analytical separation.

When we built 8 Ball Pool Online for the UCDREAMS Games Arcade, our target was crisp 60 FPS rigid-body 16-ball physics, dotted trajectory aim guides, iPhone Safari touch-drag cue control, and deterministic 1v1 WebSocket turn synchronization — all running natively in the browser with zero downloads.

Here is a breakdown of the physics loop and network synchronization model.

1. Sub-Stepped 240Hz Physics Inside a 60Hz Render Loop

Running collision checks once per animation frame (dt ≈ 16.67ms) fails during high-speed breaks because two spheres of radius $R$ can overlap by more than $2R$ in a single step. Splitting every frame into $N = 4$ or $6$ fixed micro-substeps ensures the maximum displacement per substep stays well below $0.4R$:

interface PoolBall {
  id: number;          // 0 = cue, 1..7 = solids, 8 = eight-ball, 9..15 = stripes
  x: number;
  y: number;
  vx: number;
  vy: number;
  pocketed: boolean;
}

const BALL_RADIUS = 11;
const SUBSTEPS = 6;
const CUSHION_RESTITUTION = 0.84;
const BALL_RESTITUTION = 0.96;
const ROLLING_FRICTION = 0.992; // Applied per 60Hz tick
const STOP_EPSILON = 0.04;

export function stepBilliardsFrame(balls: PoolBall[], tableBounds: {
  left: number; right: number; top: number; bottom: number;
}): boolean {
  const subFriction = Math.pow(ROLLING_FRICTION, 1 / SUBSTEPS);

  for (let s = 0; s < SUBSTEPS; s++) {
    // 1. Integrate positions
    for (const b of balls) {
      if (b.pocketed) continue;
      b.x += b.vx / SUBSTEPS;
      b.y += b.vy / SUBSTEPS;
      b.vx *= subFriction;
      b.vy *= subFriction;
      resolveCushionBounce(b, tableBounds);
    }

    // 2. Pairwise elastic collisions (O(N^2) over <= 16 balls = 120 checks/substep)
    for (let i = 0; i < balls.length; i++) {
      if (balls[i].pocketed) continue;
      for (let j = i + 1; j < balls.length; j++) {
        if (balls[j].pocketed) continue;
        resolveBallCollision(balls[i], balls[j]);
      }
    }
  }

  let anyMoving = false;
  for (const b of balls) {
    if (b.pocketed) continue;
    if (Math.hypot(b.vx, b.vy) < STOP_EPSILON) {
      b.vx = 0;
      b.vy = 0;
    } else {
      anyMoving = true;
    }
  }
  return anyMoving;
}

With at most 16 balls on the felt, pairwise collision checks total $\binom{16}{2} = 120$ pairs per substep (720 lightweight arithmetic checks per frame) — easily executing in under 0.15ms even on mid-range mobile phones.

2. Analytical Overlap Separation & Equal-Mass Impulse

Two subtle bugs break naive pool physics:

  1. Sticky racks: If two balls overlap by even 0.5px and you flip velocities without separating them along the collision normal, they repeatedly collide on the next substep and lose energy.
  2. Incorrect cut-shot angles: Resolving impulses in Cartesian $(x, y)$ instead of projecting onto the unit normal $\hat{n}$ and unit tangent $\hat{t}$ corrupts thin cut angles.
function resolveBallCollision(a: PoolBall, b: PoolBall): void {
  const dx = b.x - a.x;
  const dy = b.y - a.y;
  const distSq = dx * dx + dy * dy;
  const minDist = BALL_RADIUS * 2;

  if (distSq === 0 || distSq >= minDist * minDist) return;

  const dist = Math.sqrt(distSq);
  const nx = dx / dist;
  const ny = dy / dist;

  // Positional correction: push overlapping balls apart equally
  const overlap = (minDist - dist) * 0.5;
  a.x -= nx * overlap;
  a.y -= ny * overlap;
  b.x += nx * overlap;
  b.y += ny * overlap;

  // Relative velocity along the collision normal
  const rvx = b.vx - a.vx;
  const rvy = b.vy - a.vy;
  const velAlongNormal = rvx * nx + rvy * ny;

  // Only apply impulse if balls are approaching each other
  if (velAlongNormal > 0) return;

  const impulse = (-(1 + BALL_RESTITUTION) * velAlongNormal) * 0.5;
  a.vx -= impulse * nx;
  a.vy -= impulse * ny;
  b.vx += impulse * nx;
  b.vy += impulse * ny;
}

Because the dotted aim guide projects a virtual cue-ball ray forward until first contact with a table cushion or target sphere, computing the exact contact center $(c_x, c_y)$ gives players authentic cut-angle ghost-ball feedback before pulling back the cue stick.

3. Cushion Restitution, Pocket Jaw Geometry & Rules State

Pocket jaws and rails require special care so fast shots along a rail do not bounce off an invisible flat box before reaching a corner pocket:

  • Pocket Funneling: When a ball center crosses within the pocket mouth capture radius, it transitions cleanly out of rail-bounce bounds into pocket capture, triggering acoustic pocket drop audio.
  • Rule Engine: Tracking firstContactBallId, anyBallHitCushionAfterContact, pocketedThisTurn[], and solids/stripes group assignment cleanly handles ball-in-hand scratches, re-spots, and legal 8-ball pocket calls.

4. Lightweight 1v1 Turn-Synchronized WebSocket Protocol

Unlike twitch action games like our 200-player stickman arena Paper War or high-speed Table Tennis Online, turn-based 8 Ball Pool avoids floating-point drift across browsers by broadcasting two compact events per shot:

  1. Aim Preview (aim_update): Throttled cue angle while the active player lines up their shot so the opponent watches the cue stick rotate live.
  2. Shot Commit & Resting Snapshot (shot_commit / turn_sync): Sends the initial impulse (angle, power, cuePos) so the opponent renders the live break immediately, followed by the authoritative final (x, y, pocketed) state vector once anyMoving === false to keep both tables pixel-identical.

Play 8 Ball Pool Online & Explore the Ecosystem

Try the live 16-ball physics engine in your browser (Ranked 1v1, Private Friend Rooms, Pass & Play, or Smart AI — zero downloads):

Built by UCDREAMS Senior Engineers

Need a custom real-time web application, interactive multiplayer game, AI automation workflow, or 95+ PageSpeed WordPress site? Connect directly with our engineering team:

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.