[SYSTEM CLOCK :: 09/12/2026, 02:24:07]
██████╗  █████╗ ██████╗ ████████╗ ██████╗ ███╗   ███╗███████╗
██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔═══██╗████╗ ████║██╔════╝
██████╔╝███████║██║  ██║   ██║   ██║   ██║██╔████╔██║█████╗  
██╔══██╗██╔══██║██║  ██║   ██║   ██║   ██║██║╚██╔╝██║██╔══╝  
██║  ██║██║  ██║██████╔╝   ██║   ╚██████╔╝██║ ╚═╝ ██║███████╗
╚═╝  ╚═╝╚═╝  ╚═╝╚═════╝    ╚═╝    ╚═════╝ ╚═╝     ╚═╝╚══════╝

▎ Software Project Organization ▎

🐱

Catapult Chaos 3D

Wide Spike Wall Fortress Arcade

Score0
High Score0
Attempts0
Pull cat back towards you to aim & launch!
Slingshot Power
0%
Aim: Pull down & left/right to aim into the screen. Missed cats hit ground and scamper away to freedom!
SYSTEM ARCHITECTURE::HTML5 CANVAS & REACT 19::PRODUCTION FIELD NOTE

Engineering a 2D Verlet Physics & Collision Engine in HTML5 Canvas & React 19

A technical retrospective on building a low-latency, 60 FPS ballistic physics simulator and procedural chiptune audio synthesizer directly in the browser DOM with zero external physics libraries.

// ARCHITECTURAL OVERVIEW & DECLARATIVE REACT BRIDGING

Developing interactive browser games inside modern component libraries presents a fundamental architectural challenge: reconciling React's declarative, asynchronous reconciler with the imperative, synchronous 60 FPS animation loop required by HTML5 Canvas rendering contexts. In naive implementations, binding physics calculations to React state triggers frequent re-renders, causing garbage collection spikes and dropped frames during intensive projectile simulations.

In Catapult Chaos, the architecture cleanly decouples simulation logic from component lifecycle management. React 19 manages high-level application state—such as high scores stored in local storage, responsive UI mode switches, and full-screen transitions—while the physics simulation runs autonomously through mutable references (useRef) inside an uninterrupted requestAnimationFrame loop.

Frame Timing & High-DPI Canvas Scaling (devicePixelRatio)

Modern user displays range from standard 60Hz 1080p monitors to 120Hz ProMotion screens and high-density Retina mobile devices. Rendering on high-DPI displays without physical coordinate normalization results in blurry pixelated graphics and uneven velocity vectors across different client hardware.

To achieve crisp visual fidelity, the canvas backing store buffer is dynamically scaled against the display's native pixel density:

// High-DPI Canvas Backing Store Normalization const dpr = window.devicePixelRatio || 1; canvas.width = rect.width * dpr; canvas.height = rect.height * dpr; ctx.scale(dpr, dpr); canvas.style.width = `${rect.width}px`; canvas.style.height = `${rect.height}px`;

Furthermore, frame timing is stabilized using delta-time calculation (dt = Math.min((currentTime - lastTime) / 1000, 0.033)). Clamping dt to a maximum threshold of 33 milliseconds prevents the "spiral of death" where physics steps fall behind frame execution when backgrounding browser tabs, guaranteeing consistent physical gravity acceleration across all devices.

Verlet Numerical Integration vs Euler Trajectory Projection

Physics simulation in classical game engines typically utilizes explicit Euler integration: calculating acceleration from forces, updating velocity, and adjusting position coordinates. While computationally lightweight, explicit Euler introduces quadratic truncation errors, causing simulated bodies to artificially gain kinetic energy over parabolic arcs and drift uncontrollably.

Catapult Chaos combines two complementary physical models:

  • Predictive Euler Trajectory Guide: When the user draws back the catapult rubber band, a closed-form kinematic ballistic equation forecasts the flight path ahead of release:
    x(t) = x_0 + v_{0x} * t y(t) = y_0 + v_{0y} * t + 0.5 * gravity * t^2
    This renders a dotted trajectory guide with zero runtime integration overhead.
  • Time-Corrected Verlet Integration: Once released, projectile motion transitions to numerical Verlet integration. Velocity is implicitly preserved across consecutive position steps (x_next = 2 * x - x_prev + a * dt^2). Because Verlet integration is symplectic, it preserves the phase space volume and conserves gravitational potential energy flawlessly across rebounds and wall collisions.

Radial & Axis-Aligned Bounding Box (AABB) Collision Detection

Collision handling combines broadphase rejection with narrowphase geometric intersection. Checking complex polygons on every animation frame incurs unnecessary CPU cycles; consequently, the engine executes a multi-tiered collision pipeline:

  1. Radial Broadphase Rejection: The flying character is approximated by a circular collision hull. Distance tests against spherical target centers evaluate squared distances (dx * dx + dy * dy <= (r1 + r2) * (r1 + r2)), bypassing computationally intensive Math.sqrt() calls.
  2. Axis-Aligned Bounding Box (AABB) Boundary Clipping: Ground terrain, ceiling limits, and right-wall barriers use fast interval overlap checks. When the projectile crosses boundary thresholds, normal velocity components invert with a coefficient of restitution (restitution = 0.65) to simulate realistic rubberized rebound damping.
  3. Geometric Narrowphase Impalement: Spikes and hazards define triangular coordinate hulls. When the projectile penetrates spike vertices, linear velocities drop to zero, kinetic energy transfers into particle emission vectors, and the simulation state transitions to impaled status.

Audio Synthesis via Web Audio API AudioContext

Traditional web games rely on heavy external MP3, OGG, or WAV audio assets. This introduces latency during initial asset loading, bandwidth bloat, and CORS security issues. Catapult Chaos eliminates external sound dependencies by synthesizing all audio procedurally via the browser's native AudioContext.

The sound engine builds sound effects dynamically using oscillator nodes and gain envelopes:

  • Slingshot Release (Thwack): A rapid pitch bend descending from 220Hz to 60Hz over 80ms using an exponential frequency ramp.
  • Spike Collision (Impalement): A layered square-wave harmonic burst with an exponential gain decay curve simulating sharp metal contact.
  • 32-Bar Retro Chiptune Music: A multi-channel tracker composed of a square wave lead synthesizer, a triangle wave walking bassline, and periodic white-noise percussion envelopes sequenced at 136 BPM directly inside memory.

// FREQUENTLY ASKED QUESTIONS // 2D CANVAS PHYSICS

[ FAQ SCHEMA SYNCED ]

Q1::How does the 2.5D perspective projection calculate depth scaling on HTML5 Canvas?

The engine projects 3D spatial coordinates (X, Y, Z) onto the 2D canvas via pinhole perspective mathematics: `scale = focalLength / (focalLength + Z)`. Coordinates scale non-linearly towards the horizon, adjusting projectile radius, particle size, and spike geometry as the cat travels into the screen.

Q2::How does the cat escape state machine handle missed spike shots?

When a launched cat misses the spike wall, it rebounds and descends to the ground plane (Y = 0). The physics system halts ballistic integration, activates an autonomous running state, and randomizes escape vectors with multi-phase procedural trotting leg animations and vocalized meow sound synthesis.

Q3::How is audio synthesized without downloading external sound asset files?

Sound effects (including the drawn-out launch meow, impale fanfare, and pawstep patters) and the 32-bar chiptune music track are generated entirely at runtime through the browser's native Web Audio API (`AudioContext`). Custom oscillator waveforms are dynamically modulated with zero external audio bandwidth overhead.

Published by Rad Tome, Lead Systems Architect & Founder
✓ Validated against HTML5 Canvas & Web Audio API Specifications