Ergo AI / Examples / Build a 3D endless runner game with Three.js: a character ru

Build a 3D endless runner game with Three.js: a character ru

A neon 3D endless runner with lanes, jumps, coins and rising speed.

⚡ Build modeErgo Lite3 files
The prompt
Build a 3D endless runner game with Three.js: a character runs on a neon track, swipe or arrow keys to switch lanes and jump, obstacles and coins, rising speed, score and high score, and a stylish start screen
Build this with Ergo →

How Ergo built it

Ergo made a plan first, then worked through it step by step:

  1. Inspect button markup and JavaScript handlers
  2. Identify and fix the control failure
  3. Verify start, pause, restart, and mobile controls

Ergo's answer

I’ll trace the button handlers and script initialization, fix the failure, and verify the controls.

I found two concrete problems: stray n characters in the HTML/JavaScript (the script ends with a runtime error), and audio/storage initialization that can throw before the game controls are wired. I’m fixing those and making the UI handlers resilient.

The markup is structurally sound; the breakage is in JavaScript initialization/runtime handling. I’m removing the syntax error and ensuring audio or browser-storage failures can never block the Start/Restart buttons.

I’ve removed the fatal script error. I’m also hardening the audio initialization and switching mobile controls to standard click events so they work consistently across touch, mouse, and keyboard activation.

The main fixes are in place. I’m doing a final pass for any remaining syntax errors, mismatched button IDs, or overlays that could block clicks.

Fixed the control failure.

What was wrong

  • A stray n remained after requestAnimationFrame(animate) in script.js, causing a runtime error.
  • Sound preferences used unguarded localStorage, which can abort the entire script in restricted browser/preview contexts.
  • Audio initialization could throw when pressing Start, preventing the game state from changing.
  • Mobile controls relied solely on pointerdown, which is less reliable across browsers and assistive input.

Fixed

  • Removed stray characters from index.html and script.js.
  • Added safe storage helpers.
  • Made audio initialization and playback non-blocking.
  • Switched mobile controls to reliable click events.
  • Checked all button IDs and handlers: Start, Restart, Resume, Pause, Quit, Menu, Sound, and mobile controls.

Reload the preview and press START RUN. If the page still does not initialize, serve it through a local HTTP server rather than opening index.html directly, since browsers may block local ES-module imports from file:// URLs:

python -m http.server 8000

Then open http://localhost:8000.

Files

index.html119 lines
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
  <meta name="theme-color" content="#070512" />
  <title>Neon Rush — Endless Runner</title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet" />
  <link rel="stylesheet" href="./style.css" />
</head>
<body>
  <main id="game-shell">
    <div id="scene" aria-label="Neon Rush 3D game"></div>
    <div class="vignette"></div>
    <div class="scanlines"></div>

    <header class="hud" id="hud">
      <div class="hud-left">
        <div class="mini-brand"><span></span> NEON RUSH</div>
        <div class="score-block">
          <span class="hud-label">Score</span>
          <strong id="score">000000</strong>
        </div>
      </div>

      <div class="speed-block">
        <div class="speed-line"><span id="speed">58</span><small>KM/H</small></div>
        <div class="speed-track"><i id="speed-fill"></i></div>
      </div>

      <div class="hud-right">
        <div class="coin-counter" title="Coins collected">
          <span class="coin-icon"></span>
          <strong id="coins">0</strong>
        </div>
        <button class="icon-button" id="sound-button" aria-label="Toggle sound" title="Toggle sound">♪</button>
        <button class="icon-button pause-icon" id="pause-button" aria-label="Pause game" title="Pause (P)">Ⅱ</button>
      </div>
    </header>

    <div class="speed-toast" id="speed-toast"><span>VELOCITY</span><strong>SPEED UP</strong></div>
    <div class="damage-flash" id="damage-flash"></div>

    <section class="screen start-screen" id="start-screen">
      <div class="menu-card">
        <div class="menu-topline">
          <span class="eyebrow"><i class="live-dot"></i> NEON LEAGUE // 01</span>
          <span class="best-chip">BEST <b id="menu-best">000000</b></span>
        </div>

        <div class="title-wrap">
          <span class="title-kicker">OUTRUN THE GRID</span>
          <h1>NEON <em>RUSH</em></h1>
          <p>Chase the horizon. Switch lanes, clear the barriers,<br class="desktop-break" /> and turn every coin into momentum.</p>
        </div>

        <div class="menu-actions">
          <button class="primary-button" id="start-button">
            <span>START RUN</span><b>↗</b>
          </button>
          <div class="run-hint"><span>01</span> Three lanes. No finish line.</div>
        </div>

        <div class="controls-grid">
          <div class="control-item">
            <div class="control-icon">←</div>
            <span><b>SWITCH</b><small>A D / Arrow keys</small></span>
          </div>
          <div class="control-item">
            <div class="control-icon">↑</div>
            <span><b>JUMP</b><small>W / Space / Swipe up</small></span>
          </div>
          <div class="control-item">
            <div class="control-icon">↓</div>
            <span><b>DROP</b><small>S / Swipe down</small></span>
          </div>
        </div>
      </div>
      <div class="menu-footer"><span></span> SYSTEM READY <i></i> 60 FPS <i></i> ENDLESS MODE</div>
    </section>

    <section class="screen compact-screen hidden" id="pause-screen">
      <div class="dialog-card">
        <span class="dialog-eyebrow">RUN SUSPENDED</span>
        <h2>PAUSED</h2>
        <p>Catch your breath. The grid will wait.</p>
        <button class="primary-button" id="resume-button"><span>RESUME RUN</span><b>▶</b></button>
        <button class="text-button" id="quit-button">Return to main menu</button>
      </div>
    </section>

    <section class="screen compact-screen hidden" id="gameover-screen">
      <div class="dialog-card results-card">
        <span class="dialog-eyebrow">CONNECTION TERMINATED</span>
        <h2>RUN OVER</h2>
        <div class="new-best hidden" id="new-best">✦ NEW HIGH SCORE ✦</div>
        <div class="final-score"><span>FINAL SCORE</span><strong id="final-score">0</strong></div>
        <div class="result-stats">
          <div><span>DISTANCE</span><b><i id="final-distance">0</i><small>m</small></b></div>
          <div><span>COINS</span><b id="final-coins">0</b></div>
          <div><span>TOP SPEED</span><b><i id="final-speed">0</i><small>km/h</small></b></div>
        </div>
        <button class="primary-button" id="restart-button"><span>RUN AGAIN</span><b>↻</b></button>
        <button class="text-button" id="menu-button">Back to main menu</button>
      </div>
    </section>

    <div class="mobile-controls" id="mobile-controls">
      <button data-action="left" aria-label="Move left">←</button>
      <button class="jump-button" data-action="jump" aria-label="Jump">↑<small>JUMP</small></button>
      <button data-action="right" aria-label="Move right">→</button>
    </div>
  </main>

  <script type="module" src="./script.js"></script>
</body>
</html>
style.css604 lines
:root {
  --ink: #070512;
  --panel: rgba(10, 8, 27, 0.78);
  --cyan: #63f6ff;
  --pink: #ff3cac;
  --violet: #8d62ff;
  --text: #f5f3ff;
  --muted: #9a96b3;
  --line: rgba(255, 255, 255, 0.12);
}

* { box-sizing: border-box; }

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  overflow: hidden;
  background: var(--ink);
  color: var(--text);
  font-family: Inter, sans-serif;
}

button { font: inherit; }

button:focus-visible {
  outline: 2px solid var(--cyan);
  outline-offset: 4px;
}

#game-shell {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 320px;
  isolation: isolate;
  background: radial-gradient(circle at 50% 45%, #171034 0, #090716 52%, #04030b 100%);
}

#scene, #scene canvas {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  display: block;
}

#scene canvas { touch-action: none; }

.vignette, .scanlines, .damage-flash {
  position: absolute;
  inset: 0;
  pointer-events: none;
}

.vignette {
  z-index: 2;
  background: radial-gradient(ellipse at center, transparent 42%, rgba(2, 1, 10, 0.28) 70%, rgba(2, 1, 9, 0.78) 115%);
}

.scanlines {
  z-index: 3;
  opacity: 0.08;
  background: repeating-linear-gradient(0deg, transparent 0 3px, rgba(255,255,255,.14) 4px);
  mix-blend-mode: overlay;
}

.damage-flash {
  z-index: 8;
  opacity: 0;
  background: radial-gradient(circle, transparent 20%, rgba(255, 28, 104, .75));
}

.damage-flash.go { animation: damage .5s ease-out; }

@keyframes damage {
  0% { opacity: .9; }
  100% { opacity: 0; }
}

.hud {
  position: absolute;
  z-index: 10;
  top: 0;
  left: 0;
  right: 0;
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  align-items: start;
  padding: 26px 32px;
  opacity: 0;
  transform: translateY(-12px);
  transition: opacity .35s, transform .35s;
  pointer-events: none;
}

body.game-active .hud { opacity: 1; transform: none; }
.hud button { pointer-events: auto; }

.mini-brand {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  color: rgba(255,255,255,.64);
  font: 600 10px/1 Space Grotesk, sans-serif;
  letter-spacing: 2.5px;
}

.mini-brand span {
  width: 7px;
  height: 7px;
  transform: rotate(45deg);
  background: var(--pink);
  box-shadow: 0 0 12px var(--pink);
}

.hud-label {
  display: block;
  margin-bottom: 1px;
  color: var(--muted);
  font-size: 9px;
  font-weight: 600;
  letter-spacing: 2px;
  text-transform: uppercase;
}

#score {
  font: 600 clamp(25px, 3vw, 36px)/1 Space Grotesk, sans-serif;
  letter-spacing: 2px;
  text-shadow: 0 0 20px rgba(99,246,255,.2);
}

.speed-block {
  min-width: 150px;
  padding: 11px 16px 12px;
  border: 1px solid rgba(255,255,255,.11);
  border-radius: 12px;
  background: rgba(6, 5, 19, .42);
  backdrop-filter: blur(12px);
  text-align: center;
}

.speed-line {
  display: flex;
  justify-content: center;
  align-items: baseline;
  gap: 6px;
  font: 600 20px/1 Space Grotesk, sans-serif;
}

.speed-line small {
  color: var(--muted);
  font: 600 8px/1 Inter, sans-serif;
  letter-spacing: 1px;
}

.speed-track {
  height: 2px;
  margin-top: 9px;
  overflow: hidden;
  background: rgba(255,255,255,.12);
}

.speed-track i {
  display: block;
  width: 15%;
  height: 100%;
  background: linear-gradient(90deg, var(--cyan), var(--pink));
  box-shadow: 0 0 8px var(--cyan);
  transition: width .3s;
}

.hud-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 9px;
}

.coin-counter {
  display: flex;
  align-items: center;
  gap: 9px;
  height: 40px;
  margin-right: 5px;
  padding: 0 14px;
  border: 1px solid rgba(255,255,255,.11);
  border-radius: 20px;
  background: rgba(6,5,19,.45);
  font: 600 15px/1 Space Grotesk, sans-serif;
}

.coin-icon {
  width: 13px;
  height: 13px;
  border: 2px solid #ffe889;
  border-radius: 50%;
  background: #ffc93c;
  box-shadow: 0 0 12px rgba(255,201,60,.7), inset 0 0 4px #fff2a6;
}

.icon-button {
  width: 40px;
  height: 40px;
  padding: 0;
  border: 1px solid rgba(255,255,255,.13);
  border-radius: 50%;
  background: rgba(8,6,23,.48);
  color: white;
  cursor: pointer;
  font-size: 17px;
  backdrop-filter: blur(10px);
  transition: border-color .2s, background .2s, transform .2s;
}

.icon-button:hover { border-color: var(--cyan); background: rgba(99,246,255,.1); transform: translateY(-1px); }
.icon-button.muted { color: #69657c; }
.pause-icon { font-weight: 700; font-size: 13px; letter-spacing: -2px; }

.screen {
  position: absolute;
  z-index: 20;
  inset: 0;
  display: flex;
  align-items: center;
  overflow: auto;
}

.start-screen {
  padding: 42px clamp(24px, 6vw, 96px);
  background: linear-gradient(90deg, rgba(4,3,14,.88) 0%, rgba(4,3,14,.63) 42%, rgba(4,3,14,.08) 78%, transparent);
}

.start-screen::before {
  content: "";
  position: absolute;
  inset: 0;
  pointer-events: none;
  background: linear-gradient(180deg, rgba(4,3,14,.28), transparent 30%, transparent 70%, rgba(4,3,14,.6));
}

.menu-card {
  position: relative;
  width: min(650px, 100%);
  animation: menu-in .8s cubic-bezier(.2,.8,.2,1) both;
}

@keyframes menu-in {
  from { opacity: 0; transform: translateX(-28px); }
  to { opacity: 1; transform: none; }
}

.menu-topline {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
  margin-bottom: clamp(28px, 5vh, 54px);
}

.eyebrow, .dialog-eyebrow {
  color: var(--cyan);
  font: 600 10px/1 Space Grotesk, sans-serif;
  letter-spacing: 2.4px;
}

.live-dot {
  display: inline-block;
  width: 5px;
  height: 5px;
  margin: 0 7px 2px 0;
  border-radius: 50%;
  background: var(--cyan);
  box-shadow: 0 0 9px var(--cyan);
  animation: pulse 1.5s infinite;
}

@keyframes pulse { 50% { opacity: .35; } }

.best-chip {
  color: var(--muted);
  font-size: 9px;
  letter-spacing: 1.8px;
}

.best-chip b { margin-left: 8px; color: white; font: 600 13px/1 Space Grotesk, sans-serif; }

title-wrap { position: relative; }
.title-kicker {
  display: block;
  margin: 0 0 10px 5px;
  color: #b6aecb;
  font: 500 10px/1 Space Grotesk, sans-serif;
  letter-spacing: 5px;
}

h1 {
  margin: 0;
  font: 700 clamp(58px, 8.2vw, 112px)/.84 Space Grotesk, sans-serif;
  letter-spacing: -6px;
  white-space: nowrap;
  text-shadow: 0 5px 40px rgba(0,0,0,.35);
}

h1 em {
  color: transparent;
  font-style: normal;
  -webkit-text-stroke: 1.5px var(--pink);
  text-shadow: 0 0 28px rgba(255,60,172,.3);
}

.title-wrap p {
  max-width: 510px;
  margin: 24px 0 0 5px;
  color: #aaa4ba;
  font-size: 13px;
  line-height: 1.8;
}

.menu-actions {
  display: flex;
  align-items: center;
  gap: 23px;
  margin: 32px 0 34px;
}

.primary-button {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 230px;
  height: 58px;
  padding: 0 20px 0 24px;
  overflow: hidden;
  border: 0;
  border-radius: 4px;
  background: linear-gradient(105deg, #f5f4ff, #d8d5ef);
  color: #0b0914;
  cursor: pointer;
  font: 700 11px/1 Space Grotesk, sans-serif;
  letter-spacing: 1.8px;
  box-shadow: 0 8px 30px rgba(0,0,0,.25);
  transition: transform .2s, box-shadow .2s;
}

.primary-button::before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: var(--pink);
  box-shadow: 0 0 15px var(--pink);
}

.primary-button b { font-size: 20px; font-weight: 500; transition: transform .2s; }
.primary-button:hover { transform: translateY(-3px); box-shadow: 0 12px 38px rgba(99,246,255,.17); }
.primary-button:hover b { transform: translate(2px, -2px); }
.primary-button:active { transform: translateY(0); }

.run-hint {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #817b92;
  font-size: 10px;
}

.run-hint span { color: #d7d2e5; font: 500 10px/1 Space Grotesk, sans-serif; }

.controls-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  max-width: 580px;
  padding-top: 21px;
  border-top: 1px solid var(--line);
}

.control-item {
  display: flex;
  align-items: center;
  gap: 11px;
  min-width: 0;
}

.control-icon {
  display: grid;
  flex: 0 0 auto;
  width: 34px;
  height: 34px;
  place-items: center;
  border: 1px solid rgba(255,255,255,.15);
  border-radius: 7px;
  background: rgba(255,255,255,.035);
  color: #d7d3e4;
  font-size: 16px;
}

.control-item span { min-width: 0; }
.control-item b, .control-item small { display: block; white-space: nowrap; }
.control-item b { margin-bottom: 5px; font: 600 9px/1 Space Grotesk, sans-serif; letter-spacing: 1.5px; }
.control-item small { overflow: hidden; color: #777185; font-size: 8px; text-overflow: ellipsis; }

.menu-footer {
  position: absolute;
  left: clamp(24px, 6vw, 96px);
  bottom: 24px;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #555064;
  font: 500 7px/1 Space Grotesk, sans-serif;
  letter-spacing: 1.6px;
}

.menu-footer > span { width: 18px; height: 1px; background: var(--pink); }
.menu-footer i { width: 2px; height: 2px; border-radius: 50%; background: #555064; }

.compact-screen {
  z-index: 30;
  justify-content: center;
  padding: 24px;
  background: rgba(4,3,13,.64);
  backdrop-filter: blur(10px);
}

.dialog-card {
  width: min(440px, 100%);
  padding: 38px;
  border: 1px solid rgba(255,255,255,.12);
  border-radius: 14px;
  background: linear-gradient(145deg, rgba(20,15,43,.95), rgba(8,6,22,.96));
  box-shadow: 0 30px 100px rgba(0,0,0,.55), inset 0 1px rgba(255,255,255,.04);
  text-align: center;
  animation: dialog-in .4s cubic-bezier(.2,.8,.2,1) both;
}

@keyframes dialog-in {
  from { opacity: 0; transform: translateY(18px) scale(.97); }
  to { opacity: 1; transform: none; }
}

.dialog-card h2 {
  margin: 12px 0 10px;
  font: 700 44px/1 Space Grotesk, sans-serif;
  letter-spacing: -2px;
}

.dialog-card > p { margin: 0 0 28px; color: var(--muted); font-size: 12px; }
.dialog-card .primary-button { width: 100%; margin-top: 10px; }

.text-button {
  margin-top: 20px;
  padding: 5px;
  border: 0;
  background: none;
  color: #858094;
  cursor: pointer;
  font-size: 10px;
  transition: color .2s;
}

.text-button:hover { color: white; }

.new-best {
  margin: 16px 0 -3px;
  color: #ffe477;
  font: 600 10px/1 Space Grotesk, sans-serif;
  letter-spacing: 2px;
  text-shadow: 0 0 16px rgba(255,220,80,.4);
}

.final-score { margin: 25px 0; }
.final-score span { display: block; color: var(--muted); font-size: 8px; letter-spacing: 2px; }
.final-score strong { display: block; margin-top: 4px; font: 600 54px/1 Space Grotesk, sans-serif; letter-spacing: -2px; }

.result-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  margin-bottom: 24px;
  padding: 18px 0;
  border-top: 1px solid var(--line);
  border-bottom: 1px solid var(--line);
}

.result-stats > div + div { border-left: 1px solid var(--line); }
.result-stats span { display: block; margin-bottom: 8px; color: #777185; font-size: 7px; letter-spacing: 1.4px; }
.result-stats b { font: 600 20px/1 Space Grotesk, sans-serif; }
.result-stats small { margin-left: 3px; color: #8c879b; font: 500 8px/1 Inter, sans-serif; }

.speed-toast {
  position: absolute;
  z-index: 12;
  top: 26%;
  left: 50%;
  opacity: 0;
  transform: translate(-50%, 10px);
  text-align: center;
  pointer-events: none;
}

.speed-toast span, .speed-toast strong { display: block; }
.speed-toast span { color: var(--cyan); font-size: 8px; letter-spacing: 4px; }
.speed-toast strong { margin-top: 5px; font: 600 25px/1 Space Grotesk, sans-serif; letter-spacing: 3px; }
.speed-toast.go { animation: speed-toast 1.4s ease both; }

@keyframes speed-toast {
  0% { opacity: 0; transform: translate(-50%, 12px) scale(.9); }
  20%, 65% { opacity: 1; transform: translate(-50%, 0) scale(1); }
  100% { opacity: 0; transform: translate(-50%, -14px) scale(1.04); }
}

.mobile-controls { display: none; }
.hidden { display: none !important; }

@media (max-width: 760px) {
  .hud { padding: 18px 16px; grid-template-columns: 1fr auto 1fr; }
  .mini-brand { display: none; }
  #score { font-size: 25px; }
  .speed-block { min-width: 92px; padding: 9px 10px; }
  .speed-line { font-size: 16px; }
  .speed-line small { display: none; }
  .coin-counter { height: 34px; padding: 0 10px; margin: 0; }
  .icon-button { width: 34px; height: 34px; }
  #sound-button { display: none; }
  .hud-right { gap: 6px; }

  .start-screen {
    align-items: flex-end;
    padding: 26px 22px 82px;
    background: linear-gradient(0deg, rgba(4,3,14,.96) 0%, rgba(4,3,14,.78) 56%, rgba(4,3,14,.12) 100%);
  }
  .menu-card { width: 100%; }
  .menu-topline { margin-bottom: 24px; }
  .title-kicker { font-size: 8px; letter-spacing: 4px; }
  h1 { font-size: clamp(50px, 16.5vw, 76px); letter-spacing: -4px; }
  .title-wrap p { margin-top: 17px; font-size: 11px; line-height: 1.65; }
  .desktop-break { display: none; }
  .menu-actions { margin: 24px 0; }
  .primary-button { width: 200px; height: 54px; }
  .run-hint { max-width: 100px; line-height: 1.5; }
  .controls-grid { padding-top: 16px; }
  .control-item { display: block; text-align: center; }
  .control-icon { margin: 0 auto 8px; width: 31px; height: 31px; }
  .control-item b { font-size: 7px; }
  .control-item small { font-size: 0; }
  .control-item small::after { color: #777185; font-size: 7px; }
  .control-item:nth-child(1) small::after { content: "SWIPE / A D"; }
  .control-item:nth-child(2) small::after { content: "SWIPE UP"; }
  .control-item:nth-child(3) small::after { content: "SWIPE DOWN"; }
  .menu-footer { left: 22px; bottom: 20px; }

  .mobile-controls {
    position: absolute;
    z-index: 15;
    left: 0;
    right: 0;
    bottom: max(18px, env(safe-area-inset-bottom));
    display: none;
    justify-content: space-between;
    align-items: flex-end;
    padding: 0 22px;
    pointer-events: none;
  }
  body.game-active:not(.is-paused) .mobile-controls { display: flex; }
  .mobile-controls button {
    width: 54px;
    height: 54px;
    border: 1px solid rgba(255,255,255,.18);
    border-radius: 50%;
    background: rgba(9,7,24,.35);
    color: rgba(255,255,255,.8);
    backdrop-filter: blur(6px);
    pointer-events: auto;
    touch-action: manipulation;
  }
  .mobile-controls .jump-button {
    width: 64px;
    height: 64px;
    margin-right: 36px;
    border-color: rgba(99,246,255,.34);
    color: var(--cyan);
    font-size: 20px;
  }
  .mobile-controls small { display: block; font-size: 6px; letter-spacing: 1px; }
  .dialog-card { padding: 30px 24px; }
}

@media (max-height: 680px) and (min-width: 761px) {
  .start-screen { padding-top: 24px; padding-bottom: 45px; }
  .menu-topline { margin-bottom: 22px; }
  h1 { font-size: clamp(54px, 7.5vw, 86px); }
  .title-wrap p { margin-top: 16px; line-height: 1.55; }
  .menu-actions { margin: 20px 0; }
  .controls-grid { padding-top: 15px; }
  .menu-footer { display: none; }
}

@media (prefers-reduced-motion: reduce) {
  .menu-card, .dialog-card, .live-dot { animation: none; }
}
script.js997 lines
import * as THREE from "https://cdn.jsdelivr.net/npm/three@0.164.1/build/three.module.js";

const $ = (selector) => document.querySelector(selector);
const ui = {
  score: $("#score"),
  coins: $("#coins"),
  speed: $("#speed"),
  speedFill: $("#speed-fill"),
  menuBest: $("#menu-best"),
  finalScore: $("#final-score"),
  finalDistance: $("#final-distance"),
  finalCoins: $("#final-coins"),
  finalSpeed: $("#final-speed"),
  newBest: $("#new-best"),
  startScreen: $("#start-screen"),
  pauseScreen: $("#pause-screen"),
  gameoverScreen: $("#gameover-screen"),
  speedToast: $("#speed-toast"),
  damageFlash: $("#damage-flash"),
  soundButton: $("#sound-button"),
};

const LANES = [-2.6, 0, 2.6];
const PLAYER_Z = 3.5;
const START_SPEED = 16;
const MAX_SPEED = 42;
const SEGMENT_LENGTH = 24;
const SEGMENT_COUNT = 9;
const TRACK_SPAN = SEGMENT_LENGTH * SEGMENT_COUNT;
const BEST_KEY = "neon-rush-best-v1";
const SOUND_KEY = "neon-rush-sound-v1";

const clamp = THREE.MathUtils.clamp;
const random = (min, max) => min + Math.random() * (max - min);
const formatScore = (value) => Math.max(0, Math.floor(value)).toString().padStart(6, "0");

function loadSetting(key) {
  try {
    return window.localStorage.getItem(key);
  } catch {
    return null;
  }
}

function saveSetting(key, value) {
  try {
    window.localStorage.setItem(key, String(value));
  } catch {
    // Storage can be unavailable in private or embedded contexts.
  }
}

function loadNumber(key) {
  return Math.max(0, Number.parseInt(loadSetting(key) || "0", 10) || 0);
}

function saveNumber(key, value) {
  saveSetting(key, value);
}

let bestScore = loadNumber(BEST_KEY);
ui.menuBest.textContent = formatScore(bestScore);

class SoundFX {
  constructor() {
    this.enabled = loadSetting(SOUND_KEY) !== "off";
    this.context = null;
  }

  init() {
    if (!this.enabled) return;
    try {
      if (!this.context) {
        const AudioContext = window.AudioContext || window.webkitAudioContext;
        if (!AudioContext) return;
        this.context = new AudioContext();
      }
      if (this.context.state === "suspended") {
        const resumeResult = this.context.resume();
        if (resumeResult && typeof resumeResult.catch === "function") {
          resumeResult.catch(() => {});
        }
      }
    } catch {
      // Audio is optional; gameplay and menu controls must keep working.
      this.context = null;
    }
  }

  tone(from, to, duration, type = "sine", volume = 0.04, delay = 0) {
    if (!this.enabled) return;
    this.init();
    if (!this.context) return;
    try {
      const time = this.context.currentTime + delay;
      const oscillator = this.context.createOscillator();
      const gain = this.context.createGain();
      oscillator.type = type;
      oscillator.frequency.setValueAtTime(Math.max(20, from), time);
      oscillator.frequency.exponentialRampToValueAtTime(Math.max(20, to), time + duration);
      gain.gain.setValueAtTime(volume, time);
      gain.gain.exponentialRampToValueAtTime(0.0001, time + duration);
      oscillator.connect(gain);
      gain.connect(this.context.destination);
      oscillator.start(time);
      oscillator.stop(time + duration + 0.02);
    } catch {
      // Ignore audio-device errors without interrupting the run.
    }
  }

  jump() {
    this.tone(190, 510, 0.2, "sine", 0.055);
  }

  lane() {
    this.tone(150, 205, 0.07, "sine", 0.018);
  }

  coin() {
    this.tone(760, 1220, 0.11, "sine", 0.045);
    this.tone(1120, 1580, 0.1, "sine", 0.022, 0.05);
  }

  crash() {
    this.tone(170, 32, 0.48, "sawtooth", 0.085);
    this.tone(85, 24, 0.55, "square", 0.035, 0.03);
  }

  speedUp() {
    this.tone(320, 640, 0.16, "triangle", 0.035);
    this.tone(480, 960, 0.18, "triangle", 0.025, 0.09);
  }

  click() {
    this.tone(360, 520, 0.08, "sine", 0.025);
  }
}

const sound = new SoundFX();

function updateSoundButton() {
  ui.soundButton.textContent = sound.enabled ? "♪" : "×";
  ui.soundButton.classList.toggle("muted", !sound.enabled);
  ui.soundButton.setAttribute("aria-label", sound.enabled ? "Mute sound" : "Enable sound");
}
updateSoundButton();

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070512);
scene.fog = new THREE.FogExp2(0x090716, 0.0145);

const camera = new THREE.PerspectiveCamera(58, window.innerWidth / window.innerHeight, 0.1, 260);
camera.position.set(-3.2, 5.25, 11.5);

const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.8));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
$("#scene").appendChild(renderer.domElement);

const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const standard = (color, options = {}) => new THREE.MeshStandardMaterial({
  color,
  roughness: options.roughness ?? 0.48,
  metalness: options.metalness ?? 0.55,
  emissive: options.emissive ?? 0x000000,
  emissiveIntensity: options.emissiveIntensity ?? 1,
  flatShading: options.flatShading ?? false,
});
const neon = (color, opacity = 1) => new THREE.MeshBasicMaterial({
  color,
  transparent: opacity < 1,
  opacity,
  toneMapped: false,
});

const materials = {
  road: standard(0x10101c, { roughness: 0.72, metalness: 0.35 }),
  shoulder: standard(0x090814, { roughness: 0.85, metalness: 0.15 }),
  cyan: neon(0x55efff),
  pink: neon(0xff3cac),
  violet: neon(0x8d62ff),
  dimViolet: neon(0x4b347f),
  white: standard(0xd9dbe7, { roughness: 0.28, metalness: 0.72 }),
  runnerDark: standard(0x202033, { roughness: 0.3, metalness: 0.82 }),
  black: standard(0x090912, { roughness: 0.38, metalness: 0.72 }),
  obstacle: standard(0x272038, { roughness: 0.32, metalness: 0.75 }),
  gold: standard(0xffc93c, {
    roughness: 0.22,
    metalness: 0.8,
    emissive: 0xff9d16,
    emissiveIntensity: 1.25,
  }),
};

scene.add(new THREE.HemisphereLight(0x9184ff, 0x080510, 1.55));
const keyLight = new THREE.DirectionalLight(0xd4efff, 2.3);
keyLight.position.set(-5, 11, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -5;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 32;
keyLight.shadow.bias = -0.001;
scene.add(keyLight);
const pinkLight = new THREE.PointLight(0xff3cac, 32, 34, 2);
pinkLight.position.set(6, 4, -5);
scene.add(pinkLight);
const cyanLight = new THREE.PointLight(0x55dfff, 18, 20, 2);
cyanLight.position.set(-4, 3, 5);
scene.add(cyanLight);

function makeSun() {
  const canvas = document.createElement("canvas");
  canvas.width = 256;
  canvas.height = 256;
  const context = canvas.getContext("2d");
  const gradient = context.createLinearGradient(0, 30, 0, 226);
  gradient.addColorStop(0, "#ffe5f4");
  gradient.addColorStop(0.35, "#ff83c5");
  gradient.addColorStop(1, "#ff2188");
  context.fillStyle = gradient;
  context.beginPath();
  context.arc(128, 128, 112, 0, Math.PI * 2);
  context.fill();
  context.globalCompositeOperation = "destination-out";
  for (let y = 139; y < 230; y += 15) {
    context.fillRect(12, y, 232, 4 + (y - 139) / 24);
  }
  const texture = new THREE.CanvasTexture(canvas);
  texture.colorSpace = THREE.SRGBColorSpace;
  const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
    map: texture,
    transparent: true,
    opacity: 0.68,
    depthWrite: false,
    fog: false,
  }));
  sprite.position.set(19, 24, -155);
  sprite.scale.set(35, 35, 1);
  scene.add(sprite);
}
makeSun();

const starPositions = [];
for (let i = 0; i < 380; i++) {
  starPositions.push(random(-145, 145), random(9, 90), random(-190, -35));
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute("position", new THREE.Float32BufferAttribute(starPositions, 3));
const stars = new THREE.Points(starGeometry, new THREE.PointsMaterial({
  color: 0xb9b4ff,
  size: 0.2,
  transparent: true,
  opacity: 0.72,
  sizeAttenuation: true,
  fog: false,
}));
scene.add(stars);

const ground = new THREE.Mesh(
  new THREE.PlaneGeometry(260, 300),
  standard(0x070611, { roughness: 0.95, metalness: 0.05 }),
);
ground.rotation.x = -Math.PI / 2;
ground.position.set(0, -0.25, -75);
ground.receiveShadow = true;
scene.add(ground);

const segments = [];
function addBox(parent, material, x, y, z, sx, sy, sz) {
  const mesh = new THREE.Mesh(cubeGeometry, material);
  mesh.position.set(x, y, z);
  mesh.scale.set(sx, sy, sz);
  parent.add(mesh);
  return mesh;
}

function createTrackSegment(index) {
  const group = new THREE.Group();
  group.position.z = 18 - index * SEGMENT_LENGTH;

  const road = addBox(group, materials.road, 0, -0.11, 0, 8.55, 0.22, SEGMENT_LENGTH);
  road.receiveShadow = true;
  addBox(group, materials.shoulder, -5.8, -0.2, 0, 2.5, 0.12, SEGMENT_LENGTH);
  addBox(group, materials.shoulder, 5.8, -0.2, 0, 2.5, 0.12, SEGMENT_LENGTH);
  addBox(group, materials.cyan, -4.22, 0.035, 0, 0.055, 0.055, SEGMENT_LENGTH);
  addBox(group, materials.pink, 4.22, 0.035, 0, 0.055, 0.055, SEGMENT_LENGTH);

  for (const x of [-1.3, 1.3]) {
    for (let z = -10; z <= 10; z += 4) {
      addBox(group, materials.dimViolet, x, 0.018, z, 0.035, 0.025, 1.85);
    }
  }

  for (const z of [-8, 0, 8]) {
    const leftMat = (index + (z === 0 ? 1 : 0)) % 2 ? materials.pink : materials.cyan;
    const rightMat = leftMat === materials.pink ? materials.cyan : materials.pink;
    addBox(group, leftMat, -5.05, 0.56, z, 0.06, 1.12, 0.06);
    addBox(group, rightMat, 5.05, 0.56, z, 0.06, 1.12, 0.06);
    addBox(group, materials.black, -5.05, 0.06, z, 0.38, 0.12, 0.38);
    addBox(group, materials.black, 5.05, 0.06, z, 0.38, 0.12, 0.38);
  }

  if (index % 2 === 0) {
    const gateMaterial = index % 4 === 0 ? materials.violet : materials.dimViolet;
    addBox(group, gateMaterial, -4.7, 2.3, -5, 0.065, 4.6, 0.065);
    addBox(group, gateMaterial, 4.7, 2.3, -5, 0.065, 4.6, 0.065);
    addBox(group, gateMaterial, 0, 4.58, -5, 9.4, 0.055, 0.055);
    addBox(group, materials.pink, 0, 4.47, -5, 1.3, 0.06, 0.08);
  }

  let seed = index * 17.13 + 4;
  const seeded = () => {
    seed = (seed * 9301 + 49297) % 233280;
    return seed / 233280;
  };
  for (let side = -1; side <= 1; side += 2) {
    for (let b = 0; b < 3; b++) {
      const height = 2.5 + seeded() * 10;
      const width = 1.5 + seeded() * 3.5;
      const depth = 1.5 + seeded() * 3.5;
      const x = side * (9 + seeded() * 15);
      const z = -9 + seeded() * 18;
      const building = addBox(group, materials.black, x, height / 2 - 0.2, z, width, height, depth);
      building.material = seeded() > 0.5 ? materials.black : materials.runnerDark;
      addBox(group, side > 0 ? materials.pink : materials.cyan, x, height - 0.15, z, width * 0.68, 0.035, depth * 0.68);
    }
  }

  scene.add(group);
  segments.push(group);
}

for (let i = 0; i < SEGMENT_COUNT; i++) createTrackSegment(i);

const streakPositions = new Float32Array(44 * 6);
const streakData = [];
for (let i = 0; i < 44; i++) {
  const side = Math.random() < 0.5 ? -1 : 1;
  streakData.push({
    x: side * random(5.2, 13),
    y: random(0.5, 6),
    z: random(-115, 15),
    length: random(0.8, 3.1),
  });
}
const streakGeometry = new THREE.BufferGeometry();
streakGeometry.setAttribute("position", new THREE.BufferAttribute(streakPositions, 3));
const streakLines = new THREE.LineSegments(streakGeometry, new THREE.LineBasicMaterial({
  color: 0x8a79ff,
  transparent: true,
  opacity: 0.28,
  blending: THREE.AdditiveBlending,
}));
scene.add(streakLines);

function updateStreaks(step) {
  for (let i = 0; i < streakData.length; i++) {
    const streak = streakData[i];
    streak.z += step * 1.25;
    if (streak.z > 18) {
      streak.z = -115;
      streak.y = random(0.5, 6);
    }
    const offset = i * 6;
    streakPositions[offset] = streak.x;
    streakPositions[offset + 1] = streak.y;
    streakPositions[offset + 2] = streak.z;
    streakPositions[offset + 3] = streak.x;
    streakPositions[offset + 4] = streak.y;
    streakPositions[offset + 5] = streak.z + streak.length;
  }
  streakGeometry.attributes.position.needsUpdate = true;
}

function createRunner() {
  const root = new THREE.Group();
  const visual = new THREE.Group();
  root.add(visual);

  const torso = addBox(visual, materials.white, 0, 1.48, 0, 0.72, 0.82, 0.4);
  torso.castShadow = true;
  addBox(visual, materials.runnerDark, 0, 1.08, 0, 0.75, 0.14, 0.43);
  addBox(visual, materials.cyan, 0, 1.52, -0.213, 0.34, 0.075, 0.025);
  addBox(visual, materials.runnerDark, 0, 1.48, 0.255, 0.47, 0.52, 0.15);
  addBox(visual, materials.pink, 0, 1.55, 0.34, 0.07, 0.32, 0.025);

  const head = addBox(visual, materials.white, 0, 2.14, 0, 0.54, 0.47, 0.47);
  head.castShadow = true;
  addBox(visual, materials.black, 0, 2.16, -0.241, 0.4, 0.13, 0.025);
  addBox(visual, materials.cyan, 0, 2.17, -0.258, 0.29, 0.035, 0.018);
  addBox(visual, materials.runnerDark, 0, 2.4, 0, 0.5, 0.08, 0.43);
  addBox(visual, materials.pink, 0.2, 2.46, 0, 0.04, 0.15, 0.04);

  function makeArm(side) {
    const pivot = new THREE.Group();
    pivot.position.set(side * 0.46, 1.76, 0);
    const arm = addBox(pivot, materials.runnerDark, 0, -0.28, 0, 0.17, 0.62, 0.19);
    arm.castShadow = true;
    addBox(pivot, materials.white, 0, -0.08, 0, 0.21, 0.24, 0.23);
    addBox(pivot, materials.cyan, 0, -0.58, 0, 0.16, 0.13, 0.18);
    visual.add(pivot);
    return pivot;
  }

  function makeLeg(side) {
    const pivot = new THREE.Group();
    pivot.position.set(side * 0.21, 1.02, 0);
    const leg = addBox(pivot, materials.runnerDark, 0, -0.35, 0, 0.23, 0.72, 0.25);
    leg.castShadow = true;
    addBox(pivot, materials.white, 0, -0.22, 0, 0.26, 0.25, 0.28);
    addBox(pivot, materials.black, 0, -0.77, -0.09, 0.28, 0.17, 0.45);
    addBox(pivot, side < 0 ? materials.pink : materials.cyan, 0, -0.77, -0.315, 0.19, 0.035, 0.025);
    visual.add(pivot);
    return pivot;
  }

  const leftArm = makeArm(-1);
  const rightArm = makeArm(1);
  const leftLeg = makeLeg(-1);
  const rightLeg = makeLeg(1);

  root.position.set(0, 0, PLAYER_Z);
  scene.add(root);
  return { root, visual, leftArm, rightArm, leftLeg, rightLeg };
}

const runner = createRunner();
const shadow = new THREE.Mesh(
  new THREE.CircleGeometry(0.72, 28),
  new THREE.MeshBasicMaterial({ color: 0x000000, transparent: true, opacity: 0.36, depthWrite: false }),
);
shadow.rotation.x = -Math.PI / 2;
shadow.position.set(0, 0.018, PLAYER_Z + 0.08);
shadow.scale.set(1, 0.64, 1);
scene.add(shadow);

const obstacles = [];
const coins = [];
const coinGeometry = new THREE.TorusGeometry(0.29, 0.075, 8, 22);
const coinCoreGeometry = new THREE.CircleGeometry(0.19, 18);

function createObstacle(type, lane, z) {
  let record = obstacles.find((item) => !item.active && item.type === type);
  if (!record) {
    const group = new THREE.Group();
    if (type === "barrier") {
      const body = addBox(group, materials.obstacle, 0, 0.39, 0, 1.68, 0.72, 0.58);
      body.castShadow = true;
      addBox(group, materials.pink, 0, 0.77, 0, 1.72, 0.055, 0.61);
      addBox(group, materials.pink, -0.73, 0.4, 0.306, 0.07, 0.65, 0.035);
      addBox(group, materials.pink, 0.73, 0.4, 0.306, 0.07, 0.65, 0.035);
      for (const x of [-0.42, 0, 0.42]) {
        const stripe = addBox(group, materials.violet, x, 0.4, 0.312, 0.1, 0.48, 0.025);
        stripe.rotation.z = -0.48;
      }
      addBox(group, materials.black, 0, 0.06, 0, 1.86, 0.12, 0.78);
    } else {
      const body = addBox(group, materials.obstacle, 0, 1.1, 0, 1.88, 2.2, 0.82);
      body.castShadow = true;
      addBox(group, materials.violet, 0, 2.22, 0, 1.92, 0.06, 0.85);
      addBox(group, materials.pink, 0, 1.12, 0.427, 0.12, 1.7, 0.025);
      for (const y of [0.45, 1.1, 1.75]) {
        addBox(group, materials.black, 0, y, 0.435, 1.45, 0.12, 0.035);
      }
      addBox(group, materials.cyan, -0.77, 1.12, 0.44, 0.06, 1.6, 0.03);
      addBox(group, materials.cyan, 0.77, 1.12, 0.44, 0.06, 1.6, 0.03);
    }
    group.visible = false;
    scene.add(group);
    record = {
      group,
      type,
      active: false,
      width: type === "barrier" ? 1.68 : 1.88,
      height: type === "barrier" ? 0.8 : 2.25,
      depth: type === "barrier" ? 0.6 : 0.84,
    };
    obstacles.push(record);
  }
  record.active = true;
  record.lane = lane;
  record.group.position.set(LANES[lane], 0, z);
  record.group.visible = true;
  return record;
}

function spawnCoin(lane, z, y = 1) {
  let coin = coins.find((item) => !item.active);
  if (!coin) {
    const group = new THREE.Group();
    const ring = new THREE.Mesh(coinGeometry, materials.gold);
    group.add(ring);
    const core = new THREE.Mesh(coinCoreGeometry, materials.gold);
    core.position.z = 0.005;
    group.add(core);
    group.visible = false;
    scene.add(group);
    coin = { group, active: false, baseY: 1, phase: Math.random() * Math.PI * 2 };
    coins.push(coin);
  }
  coin.active = true;
  coin.baseY = y;
  coin.phase = Math.random() * Math.PI * 2;
  coin.group.position.set(LANES[lane], y, z);
  coin.group.rotation.set(0, Math.random() * Math.PI, 0);
  coin.group.visible = true;
}

function spawnCoinLine(lane, z, count = 6, arc = false) {
  for (let i = 0; i < count; i++) {
    const t = count === 1 ? 0 : i / (count - 1);
    const y = arc ? 1 + Math.sin(t * Math.PI) * 1.65 : 1;
    spawnCoin(lane, z - i * 2.1, y);
  }
}

function spawnObstacleWave() {
  const z = -112;
  const roll = Math.random();
  let freeLane = Math.floor(Math.random() * 3);

  if (roll < 0.5) {
    const lane = Math.floor(Math.random() * 3);
    createObstacle(Math.random() < 0.7 ? "barrier" : "block", lane, z);
    const otherLanes = [0, 1, 2].filter((item) => item !== lane);
    freeLane = otherLanes[Math.floor(Math.random() * otherLanes.length)];
  } else if (roll < 0.88) {
    for (let lane = 0; lane < 3; lane++) {
      if (lane !== freeLane) {
        createObstacle(Math.random() < 0.57 ? "barrier" : "block", lane, z);
      }
    }
  } else {
    for (let lane = 0; lane < 3; lane++) createObstacle("barrier", lane, z);
  }

  if (Math.random() < 0.78) {
    const arc = roll >= 0.88;
    spawnCoinLine(freeLane, z - 4, arc ? 7 : 5, arc);
  }
}

let gameState = "menu";
let currentLane = 1;
let speed = START_SPEED;
let distance = 0;
let coinCount = 0;
let score = 0;
let playerHeight = 0;
let verticalVelocity = 0;
let grounded = true;
let runPhase = 0;
let obstacleTimer = 1.2;
let coinTimer = 0.7;
let nextSpeedBoost = 24;
let topSpeed = START_SPEED;
let shake = 0;
let lastHudScore = -1;
let lastHudCoins = -1;
let lastHudSpeed = -1;

function updateTrack(step) {
  for (const segment of segments) {
    segment.position.z += step;
    if (segment.position.z > 42) segment.position.z -= TRACK_SPAN;
  }
  updateStreaks(step);
}

function resetObjects() {
  for (const obstacle of obstacles) {
    obstacle.active = false;
    obstacle.group.visible = false;
  }
  for (const coin of coins) {
    coin.active = false;
    coin.group.visible = false;
  }
}

function switchLane(direction) {
  if (gameState !== "playing") return;
  const next = clamp(currentLane + direction, 0, 2);
  if (next === currentLane) return;
  currentLane = next;
  sound.lane();
}

function jump() {
  if (gameState !== "playing" || !grounded) return;
  grounded = false;
  verticalVelocity = 8.5;
  sound.jump();
}

function drop() {
  if (gameState !== "playing" || grounded) return;
  verticalVelocity = Math.min(verticalVelocity, -10.5);
}

function collectCoin(coin) {
  coin.active = false;
  coin.group.visible = false;
  coinCount += 1;
  sound.coin();
}

function moveObjects(step, allowCollisions) {
  for (const obstacle of obstacles) {
    if (!obstacle.active) continue;
    const group = obstacle.group;
    const oldZ = group.position.z;
    group.position.z += step;
    if (group.position.z > 20) {
      obstacle.active = false;
      group.visible = false;
      continue;
    }
    if (!allowCollisions) continue;
    const margin = obstacle.depth / 2 + 0.46;
    const crossedPlayer = oldZ < PLAYER_Z + margin && group.position.z > PLAYER_Z - margin;
    const xClose = Math.abs(group.position.x - runner.root.position.x) < obstacle.width / 2 + 0.3;
    if (crossedPlayer && xClose && playerHeight < obstacle.height - 0.08) {
      endGame();
      return;
    }
  }

  for (const coin of coins) {
    if (!coin.active) continue;
    const oldZ = coin.group.position.z;
    coin.group.position.z += step;
    coin.group.rotation.y += 0.075 * step + 0.025;
    coin.group.position.y = coin.baseY + Math.sin(performance.now() * 0.004 + coin.phase) * 0.07;
    if (coin.group.position.z > 20) {
      coin.active = false;
      coin.group.visible = false;
      continue;
    }
    if (!allowCollisions) continue;
    const crossedPlayer = oldZ < PLAYER_Z + 1 && coin.group.position.z > PLAYER_Z - 1;
    const xClose = Math.abs(coin.group.position.x - runner.root.position.x) < 0.78;
    const yClose = Math.abs(coin.baseY - (playerHeight + 1.05)) < 1.03;
    if (crossedPlayer && xClose && yClose) collectCoin(coin);
  }
}

function updatePlayer(dt) {
  const previousX = runner.root.position.x;
  const targetX = LANES[currentLane];
  runner.root.position.x += (targetX - runner.root.position.x) * (1 - Math.exp(-13 * dt));
  const lateralVelocity = (runner.root.position.x - previousX) / Math.max(dt, 0.001);

  if (!grounded) {
    playerHeight += verticalVelocity * dt;
    verticalVelocity -= 22.5 * dt;
    if (playerHeight <= 0) {
      playerHeight = 0;
      verticalVelocity = 0;
      grounded = true;
    }
  }
  runner.root.position.y = playerHeight;

  const stride = Math.sin(runPhase);
  const airAmount = grounded ? 0 : 1;
  runner.leftLeg.rotation.x = THREE.MathUtils.lerp(stride * 0.78, -0.42, airAmount);
  runner.rightLeg.rotation.x = THREE.MathUtils.lerp(-stride * 0.78, 0.5, airAmount);
  runner.leftArm.rotation.x = THREE.MathUtils.lerp(-stride * 0.72, -0.8, airAmount);
  runner.rightArm.rotation.x = THREE.MathUtils.lerp(stride * 0.72, -0.55, airAmount);
  runner.visual.position.y = grounded ? Math.abs(Math.cos(runPhase)) * 0.055 : 0.04;
  runner.visual.rotation.z = THREE.MathUtils.lerp(
    runner.visual.rotation.z,
    clamp(-lateralVelocity * 0.025, -0.2, 0.2),
    1 - Math.exp(-10 * dt),
  );

  shadow.position.x = runner.root.position.x;
  const shadowScale = 1 - Math.min(playerHeight / 5, 0.48);
  shadow.scale.set(shadowScale, shadowScale * 0.64, shadowScale);
  shadow.material.opacity = 0.36 * shadowScale;
}

function updateHud() {
  const wholeScore = Math.floor(score);
  const shownSpeed = Math.round(speed * 3.6);
  if (wholeScore !== lastHudScore) {
    ui.score.textContent = formatScore(wholeScore);
    lastHudScore = wholeScore;
  }
  if (coinCount !== lastHudCoins) {
    ui.coins.textContent = String(coinCount);
    lastHudCoins = coinCount;
  }
  if (shownSpeed !== lastHudSpeed) {
    ui.speed.textContent = String(shownSpeed);
    lastHudSpeed = shownSpeed;
  }
  ui.speedFill.style.width = `${clamp((speed - START_SPEED) / (MAX_SPEED - START_SPEED), 0, 1) * 100}%`;
}

function showSpeedToast() {
  ui.speedToast.classList.remove("go");
  void ui.speedToast.offsetWidth;
  ui.speedToast.classList.add("go");
  sound.speedUp();
}

function startGame() {
  sound.init();
  sound.click();
  resetObjects();
  gameState = "playing";
  currentLane = 1;
  speed = START_SPEED;
  topSpeed = START_SPEED;
  distance = 0;
  coinCount = 0;
  score = 0;
  playerHeight = 0;
  verticalVelocity = 0;
  grounded = true;
  runPhase = 0;
  obstacleTimer = 1.25;
  coinTimer = 0.6;
  nextSpeedBoost = 24;
  shake = 0;
  lastHudScore = -1;
  lastHudCoins = -1;
  lastHudSpeed = -1;

  runner.root.position.set(0, 0, PLAYER_Z);
  runner.root.rotation.set(0, 0, 0);
  runner.visual.rotation.set(0, 0, 0);
  runner.visual.position.set(0, 0, 0);
  shadow.visible = true;

  ui.startScreen.classList.add("hidden");
  ui.pauseScreen.classList.add("hidden");
  ui.gameoverScreen.classList.add("hidden");
  ui.newBest.classList.add("hidden");
  document.body.classList.add("game-active");
  document.body.classList.remove("is-paused");
  updateHud();
}

function endGame() {
  if (gameState !== "playing") return;
  gameState = "gameover";
  shake = 0.34;
  sound.crash();
  if (navigator.vibrate) navigator.vibrate(70);

  const previousBest = bestScore;
  const finalValue = Math.floor(score);
  if (finalValue > bestScore) {
    bestScore = finalValue;
    saveNumber(BEST_KEY, bestScore);
  }
  ui.menuBest.textContent = formatScore(bestScore);
  ui.finalScore.textContent = formatScore(finalValue);
  ui.finalDistance.textContent = Math.floor(distance).toLocaleString();
  ui.finalCoins.textContent = String(coinCount);
  ui.finalSpeed.textContent = String(Math.round(topSpeed * 3.6));
  ui.newBest.classList.toggle("hidden", !(finalValue > previousBest && finalValue > 0));
  ui.damageFlash.classList.remove("go");
  void ui.damageFlash.offsetWidth;
  ui.damageFlash.classList.add("go");
  document.body.classList.remove("game-active", "is-paused");

  window.setTimeout(() => {
    if (gameState !== "gameover") return;
    ui.gameoverScreen.classList.remove("hidden");
  }, 520);
}

function goToMenu() {
  sound.click();
  gameState = "menu";
  resetObjects();
  currentLane = 1;
  playerHeight = 0;
  verticalVelocity = 0;
  grounded = true;
  runner.root.position.set(0, 0, PLAYER_Z);
  runner.root.rotation.set(0, 0, 0);
  runner.visual.rotation.set(0, 0, 0);
  runner.visual.position.set(0, 0, 0);
  shadow.visible = true;
  ui.startScreen.classList.remove("hidden");
  ui.pauseScreen.classList.add("hidden");
  ui.gameoverScreen.classList.add("hidden");
  document.body.classList.remove("game-active", "is-paused");
}

function pauseGame() {
  if (gameState !== "playing") return;
  gameState = "paused";
  ui.pauseScreen.classList.remove("hidden");
  document.body.classList.remove("game-active");
  document.body.classList.add("is-paused");
}

function resumeGame() {
  if (gameState !== "paused") return;
  sound.click();
  gameState = "playing";
  ui.pauseScreen.classList.add("hidden");
  document.body.classList.add("game-active");
  document.body.classList.remove("is-paused");
}

$("#start-button").addEventListener("click", startGame);
$("#restart-button").addEventListener("click", startGame);
$("#resume-button").addEventListener("click", resumeGame);
$("#pause-button").addEventListener("click", pauseGame);
$("#quit-button").addEventListener("click", goToMenu);
$("#menu-button").addEventListener("click", goToMenu);

ui.soundButton.addEventListener("click", () => {
  sound.enabled = !sound.enabled;
  saveSetting(SOUND_KEY, sound.enabled ? "on" : "off");
  updateSoundButton();
  if (sound.enabled) sound.click();
});

window.addEventListener("keydown", (event) => {
  const controlled = [
    "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Space",
    "KeyA", "KeyD", "KeyW", "KeyS", "KeyP", "Escape", "Enter", "KeyR",
  ];
  if (controlled.includes(event.code)) event.preventDefault();
  if (event.repeat) return;

  if (event.code === "KeyM") {
    ui.soundButton.click();
    return;
  }

  if (gameState === "menu" && (event.code === "Enter" || event.code === "Space")) {
    startGame();
    return;
  }
  if (gameState === "gameover" && ["Enter", "Space", "KeyR"].includes(event.code)) {
    startGame();
    return;
  }
  if ((gameState === "playing" || gameState === "paused") && ["KeyP", "Escape"].includes(event.code)) {
    if (gameState === "playing") pauseGame();
    else resumeGame();
    return;
  }
  if (gameState === "paused" && event.code === "Space") {
    resumeGame();
    return;
  }
  if (gameState !== "playing") return;

  if (event.code === "ArrowLeft" || event.code === "KeyA") switchLane(-1);
  if (event.code === "ArrowRight" || event.code === "KeyD") switchLane(1);
  if (["ArrowUp", "KeyW", "Space"].includes(event.code)) jump();
  if (event.code === "ArrowDown" || event.code === "KeyS") drop();
});

let swipe = null;
renderer.domElement.addEventListener("pointerdown", (event) => {
  if (gameState !== "playing") return;
  swipe = { id: event.pointerId, x: event.clientX, y: event.clientY };
  renderer.domElement.setPointerCapture?.(event.pointerId);
});
renderer.domElement.addEventListener("pointerup", (event) => {
  if (!swipe || swipe.id !== event.pointerId || gameState !== "playing") return;
  const dx = event.clientX - swipe.x;
  const dy = event.clientY - swipe.y;
  swipe = null;
  if (Math.max(Math.abs(dx), Math.abs(dy)) < 25) return;
  if (Math.abs(dx) > Math.abs(dy)) switchLane(dx > 0 ? 1 : -1);
  else if (dy < 0) jump();
  else drop();
});
renderer.domElement.addEventListener("pointercancel", () => { swipe = null; });

$("#mobile-controls").addEventListener("click", (event) => {
  const button = event.target.closest("button[data-action]");
  if (!button || gameState !== "playing") return;
  const action = button.dataset.action;
  if (action === "left") switchLane(-1);
  if (action === "right") switchLane(1);
  if (action === "jump") jump();
});

document.addEventListener("visibilitychange", () => {
  if (document.hidden && gameState === "playing") pauseGame();
});

function resize() {
  const width = window.innerWidth;
  const height = window.innerHeight;
  camera.aspect = width / height;
  camera.updateProjectionMatrix();
  renderer.setSize(width, height);
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.8));
}
window.addEventListener("resize", resize);

const lookTarget = new THREE.Vector3();
let previousTime = performance.now();

function animate(now) {
  requestAnimationFrame(animate);  const dt = Math.min(Math.max((now - previousTime) / 1000, 0), 0.04);
  previousTime = now;

  let step = 0;
  if (gameState === "playing") {
    speed = Math.min(MAX_SPEED, speed + 0.24 * dt);
    topSpeed = Math.max(topSpeed, speed);
    step = speed * dt;
    distance += step * 0.82;
    score = distance * 2 + coinCount * 50;
    runPhase += dt * speed * 0.67;

    if (speed >= nextSpeedBoost && speed < MAX_SPEED) {
      showSpeedToast();
      nextSpeedBoost += 8;
    }

    obstacleTimer -= dt;
    if (obstacleTimer <= 0) {
      spawnObstacleWave();
      obstacleTimer = Math.max(0.73, random(20, 28) / speed);
    }
    coinTimer -= dt;
    if (coinTimer <= 0) {
      const lane = Math.floor(Math.random() * 3);
      const arc = Math.random() < 0.38;
      spawnCoinLine(lane, -108, arc ? 7 : 6, arc);
      coinTimer = random(1.65, 2.7);
    }

    updateTrack(step);
    updatePlayer(dt);
    moveObjects(step, true);
    updateHud();
  } else if (gameState === "menu") {
    step = 5 * dt;
    runPhase += dt * 4.2;
    updateTrack(step);
    updatePlayer(dt);
  } else if (gameState === "gameover") {
    speed = Math.max(0, speed - 24 * dt);
    step = speed * dt;
    updateTrack(step);
    moveObjects(step, false);
    runner.visual.rotation.x = THREE.MathUtils.lerp(runner.visual.rotation.x, -1.15, 1 - Math.exp(-4 * dt));
    runner.visual.position.y = Math.max(-0.45, runner.visual.position.y - dt * 0.8);
  }

  const cameraEase = 1 - Math.exp(-3.2 * dt);
  const desiredCameraX = gameState === "menu" ? -3.2 : runner.root.position.x * 0.18;
  camera.position.x = THREE.MathUtils.lerp(camera.position.x, desiredCameraX, cameraEase);
  camera.position.y = 5.25 + (gameState === "playing" ? playerHeight * 0.07 : 0);
  camera.position.z = 11.5;

  if (shake > 0) {
    shake = Math.max(0, shake - dt);
    camera.position.x += random(-shake, shake);
    camera.position.y += random(-shake, shake) * 0.6;
  }

  const targetFov = gameState === "playing"
    ? 58 + clamp((speed - START_SPEED) / (MAX_SPEED - START_SPEED), 0, 1) * 6
    : 58;
  if (Math.abs(camera.fov - targetFov) > 0.01) {
    camera.fov = THREE.MathUtils.lerp(camera.fov, targetFov, 1 - Math.exp(-3 * dt));
    camera.updateProjectionMatrix();
  }

  lookTarget.set(
    gameState === "menu" ? -0.8 : runner.root.position.x * 0.08,
    1.02 + playerHeight * 0.08,
    -9,
  );
  camera.lookAt(lookTarget);
  renderer.render(scene, camera);
}

requestAnimationFrame(animate);
Want one like this?Start from this prompt and change anything you like.
Build your own →

← All examples