Overview
The Ball in a Spinning Hexagon & Polygon Collision Lab is an advanced interactive physical simulation and acoustic visualizer designed to demonstrate classical rotational mechanics, energy transfer, non-inertial reference frame dynamics, and real-time algorithmic sound synthesis. At its core, the application models the motion of one or multiple localized mass particles (balls) trapped inside a rotating regular polygon $P_N$ with $N$ vertices. As the surrounding polygonal container rotates with angular velocity $\vec{\omega} = \omega \hat{k}$ under the influence of uniform downward gravitational acceleration $\vec{g} = -g \hat{j}$, the enclosed particles undergo complex chaotic trajectories driven by linear momentum, centrifugal forces, surface friction, and restitution coefficients.
When a mass particle collides with a boundary edge of the rotating polygon, linear kinetic energy is exchanged between the moving wall and the particle. Because the polygon is rotating around a fixed spatial center $(X_c, Y_c)$, every point on a boundary wall possesses a non-zero tangential velocity vector $\vec{v}_{wall} = \vec{\omega} \times \vec{r}$, where $\vec{r}$ represents the position vector from the rotation center to the exact point of collision impact. Consequently, bouncing off a moving wall can either impart kinetic energy to the ball or absorb energy from it, giving rise to unpredictable deterministic chaos and harmonic acoustic patterns.
To provide an educational bridge between physics and musical acoustics, every collision event triggers an instantaneous audio synthesizer pulse synthesized via the Web Audio API. The fundamental frequency $f_{sound}$ generated upon collision is mapped to musical scales (Pentatonic, Harmonic Minor, Major Triads, or Chromatic) and influenced by the contact location and impact velocity $\| \vec{v}_{impact} \|$. This creates a dynamic acoustic feedback loop where physical energy transformations manifest directly as musical phrases and rhythmic patterns.
How to Use
Interacting with the lab workspace is intuitive and highly visual. The main viewing viewport displays the rotating polygon, enclosed particles, motion trails, and diagnostic vector grids. You can directly interact with the physical simulation through touch or cursor gestures:
- Interactive Impulse Injection: Clicking or dragging anywhere on the black canvas workspace calculates a target vector from each active ball toward the click coordinates $(x_{mouse}, y_{mouse})$, applying an instant impulse velocity $\Delta \vec{v} = 5 \cdot \hat{u}$ in the direction of the cursor. This allows you to launch balls against fast-rotating walls or rescue trapped particles.
- Start Demo Mode: Located at the top of the control panel, clicking the Start Demo button activates an automated presentation routine. In Demo Mode, the laboratory dynamically sweeps through rotation speeds, shifts gravity vectors, alters polygon side counts $N$, and launches periodic pulse forces to showcase acoustic chaos and mechanical resonance. Moving or clicking the canvas or modifying any slider will instantly interrupt the demo and restore your exact baseline workspace configuration.
- Reset Baseline: The Reset Baseline action button immediately restores all physics parameters ($g$, $\omega$, $N$, ball counts, restitution $e$, friction $\mu$) and particle position states back to their default reference values without requiring confirmation dialogs.
- Audio Synth Configuration: Click the Sound ON/OFF button (`#soundToggleBtn`) to enable sound synthesis. Select your preferred oscillator timbre (Sine, Triangle, Square, Sawtooth) and harmonic scale (Pentatonic, Harmonic Minor, Major Chord, or Chromatic) to listen to the collision rhythms.
- Parameter Sliders: Expand the Simulation Control Parameters accordion fold to fine-tune gravity $g \in [0, 2]$, angular velocity $\omega \in [-0.05, 0.05] \text{ rad/frame}$, polygon side geometry $N \in [3, 10]$, particle counts $N_{balls} \in [1, 25]$, restitution coefficient $e \in [0.5, 1.0]$, and tangential edge friction $\mu \in [0.80, 1.00]$.
Technical Details
Achieving accurate collision dynamics inside a rotating polygon without tunneling artifacts requires a multi-stage physical integration and collision resolution engine. The core physics loop operates at $S = 8$ discrete sub-steps per animation frame ($\Delta t = \frac{1}{8}$). During each sub-step, the differential equations of motion for each particle are solved sequentially:
$$ \vec{v}(t + \Delta t) = \left( \vec{v}(t) + \vec{g} \Delta t \right) \cdot \alpha^{\Delta t} $$
$$ \vec{x}(t + \Delta t) = \vec{x}(t) + \vec{v}(t + \Delta t) \Delta t $$
where $\alpha = 0.999$ denotes the air resistance damping factor. Simultaneously, the polygon rotation angle updates as $\theta_{rot}(t + \Delta t) = \theta_{rot}(t) + \omega \Delta t$. For a regular polygon with $N$ sides and radius $R$ centered at $(X_c, Y_c)$, the instantaneous spatial positions of the $N$ vertices $V_i = (x_i, y_i)$ are given by:
$$ x_i = X_c + R \cos\left( \theta_{rot} + \frac{2\pi i}{N} \right), \quad y_i = Y_c + R \sin\left( \theta_{rot} + \frac{2\pi i}{N} \right) \quad \text{for } i \in \{0, 1, \dots, N-1\} $$
For each particle centered at position $P = (x, y)$ with radius $r$, the collision engine computes the closest point $C_i$ on every boundary segment $A B = (V_i, V_{(i+1) \bmod N})$. Defining the edge vector $\vec{E} = B - A$ and particle relative vector $\vec{V} = P - A$, the projection scalar $t$ is calculated and clamped to $[0, 1]$:
$$ t = \text{clamp}\left( \frac{\vec{V} \cdot \vec{E}}{\| \vec{E} \|^2}, 0, 1 \right), \quad C_i = A + t \vec{E} $$
If the Euclidean distance $d = \| P - C_i \|$ falls below particle radius $r$, a collision occurs with penetration depth $p = r - d$. The inward unit normal vector $\hat{n}$ is evaluated towards the polygon center $(X_c, Y_c)$. The wall velocity $\vec{v}_{wall}$ at point $C_i$ resulting from rotation $\vec{\omega} = (0, 0, \omega)$ is:
$$ \vec{r} = C_i - (X_c, Y_c), \quad \vec{v}_{wall} = \left( -\omega \cdot r_y, \; \omega \cdot r_x \right) $$
The relative collision velocity $\vec{v}_{rel} = \vec{v}_{ball} - \vec{v}_{wall}$ is decomposed into normal component $v_n = \vec{v}_{rel} \cdot \hat{n}$ and tangential vector $\vec{v}_t = \vec{v}_{rel} - v_n \hat{n}$. If $v_n < 0$ (the ball is approaching the wall), inelastic impact impulse formulas update the post-collision relative velocity $\vec{v}_{rel}'$:
$$ \vec{v}_{rel}' = -e \cdot v_n \hat{n} + \mu \cdot \vec{v}_t $$
$$ \vec{v}_{ball}' = \vec{v}_{rel}' + \vec{v}_{wall} $$
The ball position is immediately corrected along normal $\hat{n}$ by penetration distance $p$ to prevent interpenetration during multi-body crowding. Furthermore, high-DPI display normalization automatically resizes the backing canvas buffers according to `window.devicePixelRatio` ($DPR$) while preserving CSS layout geometry, eliminating rendering blur on retina monitors without triggering layout feedback loops.
Future Directions
Future development iterations of the spinning polygon collision laboratory will expand both physical complexity and sound synthesis depth:
- Inter-Particle Collisions ($2\text{D}$ Elastic Impulse): Integration of particle-to-particle momentum conservation algorithms using spatial hashing and distance partitioning grids to enable hundreds of simultaneous colliding spheres with energy exchange.
- Deformable Elastic Walls: Implementation of mass-spring mesh dampeners along polygon boundary edges to simulate flexible walls that deform upon particle impact, storing potential elastic strain energy $U = \frac{1}{2} k \Delta x^2$.
- Spatialized Audio Panning & Web MIDI Integration: Implementation of Web Audio API 3D PannerNode HRTF spatialization based on canvas coordinates $(x, y)$, alongside Web MIDI output drivers to allow physical collisions to trigger external hardware synthesizers in real time.