<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>VELOCITY X - 第一人称跑酷</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { overflow: hidden; background: #000; font-family: 'Segoe UI', sans-serif; }
        canvas { display: block; }
        #hud { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 10; }
        .score-display { position: absolute; top: 20px; left: 50%; transform: translateX(-50%); font-size: 48px; font-weight: 900; color: #fff; text-shadow: 0 0 30px rgba(0,200,255,0.8), 0 4px 8px rgba(0,0,0,0.5); letter-spacing: 3px; }
        .speed-indicator { position: absolute; bottom: 30px; left: 50%; transform: translateX(-50%); text-align: center; }
        .speed-bar { width: 220px; height: 4px; background: rgba(255,255,255,0.1); border-radius: 2px; overflow: hidden; margin-top: 8px; }
        .speed-fill { height: 100%; width: 20%; background: linear-gradient(90deg, #00ffcc, #00aaff, #ff00ff); border-radius: 2px; transition: width 0.3s; }
        .speed-text { color: rgba(255,255,255,0.5); font-size: 11px; letter-spacing: 4px; text-transform: uppercase; }
        .combo-display { position: absolute; top: 85px; left: 50%; transform: translateX(-50%); font-size: 22px; font-weight: bold; color: #ffcc00; text-shadow: 0 0 20px rgba(255,200,0,0.8); opacity: 0; transition: all 0.2s; }
        .combo-display.show { opacity: 1; animation: pop 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55); }
        @keyframes pop { 0% { transform: translateX(-50%) scale(2); } 100% { transform: translateX(-50%) scale(1); } }
        .scene-announce { position: absolute; top: 40%; left: 50%; transform: translate(-50%, -50%); font-size: 36px; font-weight: 900; color: #fff; text-shadow: 0 0 40px currentColor; opacity: 0; letter-spacing: 8px; text-transform: uppercase; pointer-events: none; white-space: nowrap; }
        .scene-announce.show { animation: sceneIn 2s ease forwards; }
        @keyframes sceneIn { 0% { opacity: 0; transform: translate(-50%, -50%) scale(0.5); letter-spacing: 20px; } 20% { opacity: 1; transform: translate(-50%, -50%) scale(1.1); letter-spacing: 8px; } 30% { transform: translate(-50%, -50%) scale(1); } 70% { opacity: 1; } 100% { opacity: 0; transform: translate(-50%, -60%) scale(1); } }
        .near-miss-text { position: absolute; top: 55%; left: 50%; transform: translate(-50%, -50%); font-size: 24px; font-weight: bold; color: #00ff88; text-shadow: 0 0 15px rgba(0,255,136,0.8); opacity: 0; pointer-events: none; }
        .near-miss-text.show { animation: nmAnim 0.8s ease forwards; }
        @keyframes nmAnim { 0% { opacity: 1; transform: translate(-50%, -50%) scale(0.5) rotate(-5deg); } 30% { transform: translate(-50%, -50%) scale(1.3) rotate(2deg); } 100% { opacity: 0; transform: translate(-50%, -80%) scale(1) rotate(0deg); } }
        .vignette { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: radial-gradient(ellipse at center, transparent 55%, rgba(0,0,0,0.5) 100%); pointer-events: none; }
        .speed-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; opacity: 0; transition: opacity 0.5s; background: radial-gradient(ellipse at center, transparent 30%, rgba(0,100,255,0.1) 100%); }
        .speed-overlay.active { opacity: 1; }
        .boost-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; opacity: 0; background: radial-gradient(ellipse at center, transparent 20%, rgba(255,100,0,0.2) 100%); transition: opacity 0.3s; }
        .boost-overlay.active { opacity: 1; }
        .flash { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; opacity: 0; z-index: 50; }
        .flash.red { background: rgba(255,0,0,0.4); }
        .flash.white { background: rgba(255,255,255,0.6); }
        .flash.active { animation: flashAnim 0.3s ease; }
        @keyframes flashAnim { 0% { opacity: 1; } 100% { opacity: 0; } }
        #startScreen, #deathScreen { position: fixed; top: 0; left: 0; width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; background: rgba(0,0,0,0.9); z-index: 100; pointer-events: all; }
        #deathScreen { display: none; }
        .game-title { font-size: 64px; font-weight: 900; background: linear-gradient(135deg, #00ffcc, #0088ff, #ff00cc, #ffcc00); background-size: 300% 300%; -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; animation: gradientShift 3s ease infinite; margin-bottom: 5px; }
        @keyframes gradientShift { 0%, 100% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } }
        .game-sub { color: rgba(255,255,255,0.4); font-size: 14px; letter-spacing: 8px; margin-bottom: 50px; text-transform: uppercase; }
        .btn { padding: 16px 50px; font-size: 18px; font-weight: bold; background: linear-gradient(135deg, #00ffcc, #0088ff); color: #000; border: none; border-radius: 50px; cursor: pointer; transition: all 0.3s; letter-spacing: 3px; text-transform: uppercase; }
        .btn:hover { transform: scale(1.08); box-shadow: 0 0 40px rgba(0,255,200,0.4); }
        .controls { margin-top: 40px; color: rgba(255,255,255,0.35); font-size: 13px; text-align: center; line-height: 2.4; }
        .controls kbd { background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.15); padding: 2px 8px; border-radius: 4px; color: #00ffcc; }
        .death-score { font-size: 72px; font-weight: 900; color: #fff; margin: 15px 0; }
        .death-label { font-size: 14px; color: rgba(255,255,255,0.4); letter-spacing: 6px; text-transform: uppercase; }
        .death-best { color: #ffcc00; font-size: 15px; margin-top: 8px; }
        .tilt-indicator { position: absolute; bottom: 80px; left: 50%; transform: translateX(-50%); width: 60px; height: 3px; background: rgba(255,255,255,0.1); border-radius: 2px; }
        .tilt-dot { position: absolute; top: -3px; left: 50%; width: 8px; height: 8px; background: #00ffcc; border-radius: 50%; transform: translateX(-50%); transition: left 0.1s; box-shadow: 0 0 8px rgba(0,255,200,0.8); }
        @media (max-width: 600px) { .game-title { font-size: 44px; } .game-sub { font-size: 10px; letter-spacing: 5px; margin-bottom: 35px; } .controls { padding: 0 18px; font-size: 11px; } .score-display { font-size: 40px; } .scene-announce { font-size: 22px; letter-spacing: 4px; } }
    </style>
</head>
<body>
    <div class="vignette"></div>
    <div class="speed-overlay" id="speedOverlay"></div>
    <div class="boost-overlay" id="boostOverlay"></div>
    <div class="flash" id="flash"></div>
    <div id="hud">
        <div class="score-display" id="score">0</div>
        <div class="combo-display" id="combo"></div>
        <div class="scene-announce" id="sceneAnnounce"></div>
        <div class="near-miss-text" id="nearMiss">NEAR MISS +50</div>
        <div class="speed-indicator"><div class="speed-text">VELOCITY</div><div class="speed-bar"><div class="speed-fill" id="speedFill"></div></div></div>
        <div class="tilt-indicator"><div class="tilt-dot" id="tiltDot"></div></div>
    </div>
    <div id="startScreen">
        <div class="game-title">VELOCITY X</div>
        <div class="game-sub">First Person Parkour</div>
        <button class="btn" onclick="startGame()">开始奔跑</button>
        <div class="controls"><kbd>A</kbd><kbd>D</kbd> / <kbd>←</kbd><kbd>→</kbd> 移动 &nbsp; <kbd>W</kbd><kbd>空格</kbd> 跳跃 &nbsp; <kbd>S</kbd> 下滑<br>穿越特殊区域 · 擦身得分 · 感受速度</div>
    </div>
    <div id="deathScreen">
        <div class="death-label">FINAL SCORE</div>
        <div class="death-score" id="finalScore">0</div>
        <div class="death-best" id="bestScore">BEST: 0</div><br><br>
        <button class="btn" onclick="restartGame()">再来一次</button>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <script>
    // ==================== 核心变量 ====================
    let scene, camera, renderer;
    let gameRunning = false;
    let score = 0, bestScore = 0, frame = 0;
    let speed = 0.4, baseSpeed = 0.4, maxSpeed = 1.4;
    let playerX = 0, targetX = 0, playerY = 1.6;
    let isJumping = false, isSliding = false;
    let jumpVel = 0, gravity = -0.02;
    let obstacles = [], groundSegs = [], envObjects = [], particles = [];
    let comboCount = 0, comboTimer = 0;
    let keys = {};
    let slideTimer = null; // 修复:统一管理滑铲计时器

    // 镜头系统
    let camRoll = 0, camRollTarget = 0, camRollVel = 0;
    let camPitch = 0, camPitchTarget = 0;
    let camShakeX = 0, camShakeY = 0;
    let camBob = 0;
    let landingImpact = 0;

    // 场景系统
    let currentScene = 'city';
    let sceneTimer = 0;
    let sceneDuration = 600;
    let transitioning = false;
    let boostActive = false;
    let boostTimer = 0;

    const TRACK_W = 12;
    const LANE_W = 4;

    function init() {
        scene = new THREE.Scene();
        scene.fog = new THREE.FogExp2(0x0a0015, 0.012);
        camera = new THREE.PerspectiveCamera(85, innerWidth/innerHeight, 0.1, 250);
        camera.position.set(0, 1.6, 0);
        renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
        renderer.setSize(innerWidth, innerHeight);
        renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
        renderer.shadowMap.enabled = true;
        renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        document.body.insertBefore(renderer.domElement, document.getElementById('hud'));
        scene.add(new THREE.AmbientLight(0x334455, 0.4));
        const mainLight = new THREE.DirectionalLight(0xffffff, 0.6);
        mainLight.position.set(5, 10, 5); mainLight.castShadow = true; scene.add(mainLight);
        const playerLight = new THREE.PointLight(0x00ccff, 0.8, 15);
        playerLight.position.set(0, 3, -3); scene.add(playerLight);
        createTrack();
        createCityEnv();
        addEventListener('keydown', e => { keys[e.code] = true; handleKey(e); });
        addEventListener('keyup', e => keys[e.code] = false);
        addEventListener('resize', onResize);
        let tx = 0, ty = 0;
        addEventListener('touchstart', e => { if (!e.touches.length) return; tx = e.touches[0].clientX; ty = e.touches[0].clientY; }, { passive: true });
        addEventListener('touchend', e => {
            if (!gameRunning || !e.changedTouches.length) return;
            const dx = e.changedTouches[0].clientX - tx;
            const dy = e.changedTouches[0].clientY - ty;
            if (Math.abs(dx) > Math.abs(dy)) {
                if (dx > 35) targetX = Math.min(targetX + LANE_W, TRACK_W/2 - 1);
                else if (dx < -35) targetX = Math.max(targetX - LANE_W, -TRACK_W/2 + 1);
            } else {
                if (dy < -35) doJump();
                else if (dy > 35) doSlide();
            }
        }, { passive: true });
        animate();
    }

    function createTrack() {
        for (let i = 0; i < 35; i++) {
            const seg = buildGroundSeg(i); seg.position.z = -i * 7; scene.add(seg); groundSegs.push(seg);
        }
    }
    function buildGroundSeg(idx) {
        const g = new THREE.Group();
        const plane = new THREE.Mesh(new THREE.PlaneGeometry(TRACK_W, 7), new THREE.MeshPhongMaterial({ color: 0x111122, emissive: 0x050510, shininess: 60 }));
        plane.rotation.x = -Math.PI/2; plane.receiveShadow = true; g.add(plane);
        const lineMat = new THREE.MeshBasicMaterial({ color: 0x00ffcc, transparent: true, opacity: 0.4 });
        for (let x = -TRACK_W/2; x <= TRACK_W/2; x += LANE_W) {
            const line = new THREE.Mesh(new THREE.PlaneGeometry(0.04, 7), lineMat);
            line.rotation.x = -Math.PI/2; line.position.set(x, 0.01, 0); g.add(line);
        }
        const edgeL = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.4, 7), new THREE.MeshBasicMaterial({ color: 0xff0055 }));
        edgeL.position.set(-TRACK_W/2 - 0.1, 0.2, 0); g.add(edgeL);
        const edgeR = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.4, 7), new THREE.MeshBasicMaterial({ color: 0x0055ff }));
        edgeR.position.set(TRACK_W/2 + 0.1, 0.2, 0); g.add(edgeR);
        return g;
    }

    function createCityEnv() {
        for (let i = 0; i < 50; i++) {
            const side = i % 2 === 0 ? -1 : 1;
            const h = 4 + Math.random() * 14, w = 1.5 + Math.random() * 2;
            const geo = new THREE.BoxGeometry(w, h, w);
            const mat = new THREE.MeshPhongMaterial({ color: 0x0a0a1e, emissive: new THREE.Color().setHSL(Math.random(), 0.7, 0.02) });
            const b = new THREE.Mesh(geo, mat);
            b.position.set(side * (TRACK_W/2 + 3 + Math.random() * 6), h/2, -i * 5 - Math.random() * 3);
            scene.add(b); envObjects.push(b);
            if (Math.random() > 0.5) {
                const nGeo = new THREE.BoxGeometry(0.08, h * 0.7, 0.08);
                const nColor = [0xff0066, 0x00ffcc, 0xffcc00, 0x8800ff, 0x00aaff][Math.floor(Math.random()*5)];
                const neon = new THREE.Mesh(nGeo, new THREE.MeshBasicMaterial({ color: nColor }));
                neon.position.set(b.position.x + (side > 0 ? -w/2 - 0.1 : w/2 + 0.1), h/2, b.position.z);
                scene.add(neon); envObjects.push(neon);
            }
        }
        for (let i = 0; i < 12; i++) {
            const arch = new THREE.Mesh(new THREE.TorusGeometry(TRACK_W/2 + 2, 0.15, 8, 32, Math.PI), new THREE.MeshBasicMaterial({ color: 0x222244, transparent: true, opacity: 0.6 }));
            arch.position.set(0, 0, -i * 20); arch.rotation.z = Math.PI; scene.add(arch); envObjects.push(arch);
        }
    }

    function switchScene() {
        const scenes = ['city', 'tunnel', 'space', 'neon', 'boost'];
        const next = scenes[Math.floor(Math.random() * scenes.length)];
        if (next === currentScene) return;
        currentScene = next; sceneTimer = 0; sceneDuration = 400 + Math.random() * 300;
        const announce = document.getElementById('sceneAnnounce');
        const names = { city: '🌃 霓虹都市', tunnel: '🚇 极速隧道', space: '🌌 太空漫步', neon: '🌈 彩虹走廊', boost: '🔥 加速地带' };
        const colors = { city: '#00ccff', tunnel: '#ff6600', space: '#8844ff', neon: '#ff00cc', boost: '#ffcc00' };
        announce.textContent = names[next]; announce.style.color = colors[next];
        announce.classList.remove('show'); void announce.offsetWidth; announce.classList.add('show');
        triggerFlash('white');
        const fogColors = { city: 0x0a0015, tunnel: 0x1a0500, space: 0x000011, neon: 0x0a000a, boost: 0x0a0a00 };
        scene.fog.color.setHex(fogColors[next]);
        if (next === 'boost') {
            boostActive = true; boostTimer = 180;
            document.getElementById('boostOverlay').classList.add('active');
        } else {
            boostActive = false; document.getElementById('boostOverlay').classList.remove('active');
        }
    }

    function spawnObstacle() {
        const types = ['wall', 'low', 'overhead', 'moving', 'double', 'narrow', 'spinning', 'tripleLow', 'laser'];
        const type = types[Math.floor(Math.random() * types.length)];
        const z = -130;
        const matColors = { city: 0xff2200, tunnel: 0xff6600, space: 0x8844ff, neon: 0xff00cc, boost: 0xffcc00 };
        const baseColor = matColors[currentScene] || 0xff2200;
        switch(type) {
            case 'wall': {
                const lane = (Math.floor(Math.random()*3)-1) * LANE_W;
                const m = new THREE.Mesh(new THREE.BoxGeometry(LANE_W - 0.5, 5, 1.2), new THREE.MeshPhongMaterial({ color: baseColor, emissive: 0x220000, transparent: true, opacity: 0.9 }));
                m.position.set(lane, 2.5, z); m.userData = { type: 'wall', w: LANE_W - 0.5, h: 5 };
                addEdges(m, baseColor); scene.add(m); obstacles.push(m); break;
            }
            case 'low': {
                const lane = (Math.floor(Math.random()*3)-1) * LANE_W;
                const m = new THREE.Mesh(new THREE.BoxGeometry(LANE_W - 0.5, 1.2, 1.5), new THREE.MeshPhongMaterial({ color: 0xffaa00, emissive: 0x331100 }));
                m.position.set(lane, 0.6, z); m.userData = { type: 'low', w: LANE_W - 0.5, h: 1.2 };
                addEdges(m, 0xffaa00); scene.add(m); obstacles.push(m); break;
            }
            case 'overhead': {
                const lane = (Math.floor(Math.random()*3)-1) * LANE_W;
                const m = new THREE.Mesh(new THREE.BoxGeometry(LANE_W - 0.5, 2, 1), new THREE.MeshPhongMaterial({ color: 0x9900ff, emissive: 0x220044 }));
                m.position.set(lane, 3.2, z); m.userData = { type: 'overhead', w: LANE_W - 0.5, h: 2, bottomY: 2.2 };
                addEdges(m, 0x9900ff); scene.add(m); obstacles.push(m); break;
            }
            case 'moving': {
                const m = new THREE.Mesh(new THREE.BoxGeometry(2.5, 3.5, 1), new THREE.MeshPhongMaterial({ color: 0x00ff88, emissive: 0x003322 }));
                m.position.set(0, 1.75, z); m.userData = { type: 'moving', w: 2.5, h: 3.5, spd: 0.04 + Math.random()*0.06, dir: 1 };
                addEdges(m, 0x00ff88); scene.add(m); obstacles.push(m); break;
            }
            case 'double': {
                const gap = Math.floor(Math.random()*3)-1;
                for (let l = -1; l <= 1; l++) {
                    if (l === gap) continue;
                    const m = new THREE.Mesh(new THREE.BoxGeometry(LANE_W - 0.5, 4.5, 1), new THREE.MeshPhongMaterial({ color: baseColor, emissive: 0x110000 }));
                    m.position.set(l * LANE_W, 2.25, z); m.userData = { type: 'wall', w: LANE_W - 0.5, h: 4.5 };
                    addEdges(m, baseColor); scene.add(m); obstacles.push(m);
                }
                break;
            }
            case 'narrow': {
                const gapX = (Math.random()-0.5) * (TRACK_W - 5);
                const lw = gapX + TRACK_W/2 - 1.5, rw = TRACK_W/2 - gapX - 1.5;
                if (lw > 1) {
                    const m = new THREE.Mesh(new THREE.BoxGeometry(lw, 5, 1), new THREE.MeshPhongMaterial({ color: 0x0088ff, emissive: 0x001133 }));
                    m.position.set(-TRACK_W/2 + lw/2, 2.5, z); m.userData = { type: 'wall', w: lw, h: 5 };
                    addEdges(m, 0x0088ff); scene.add(m); obstacles.push(m);
                }
                if (rw > 1) {
                    const m = new THREE.Mesh(new THREE.BoxGeometry(rw, 5, 1), new THREE.MeshPhongMaterial({ color: 0x0088ff, emissive: 0x001133 }));
                    m.position.set(TRACK_W/2 - rw/2, 2.5, z); m.userData = { type: 'wall', w: rw, h: 5 };
                    addEdges(m, 0x0088ff); scene.add(m); obstacles.push(m);
                }
                break;
            }
            case 'spinning': {
                const m = new THREE.Mesh(new THREE.BoxGeometry(5, 0.5, 0.5), new THREE.MeshPhongMaterial({ color: 0xff4400, emissive: 0x331100 }));
                m.position.set(0, 1.5, z); m.userData = { type: 'spinning', w: 5, h: 0.5, rotSpeed: 0.03 + Math.random()*0.03 };
                addEdges(m, 0xff4400); scene.add(m); obstacles.push(m); break;
            }
            case 'tripleLow': {
                for (let l = -1; l <= 1; l++) {
                    const m = new THREE.Mesh(new THREE.BoxGeometry(LANE_W - 0.5, 1.2, 1.5), new THREE.MeshPhongMaterial({ color: 0xffcc00, emissive: 0x553300, emissiveIntensity: 0.7 }));
                    m.position.set(l * LANE_W, 0.6, z); m.userData = { type: 'low', w: LANE_W - 0.5, h: 1.2 };
                    addEdges(m, 0xffcc00); scene.add(m); obstacles.push(m);
                }
                break;
            }
            case 'laser': {
                const beam = new THREE.Mesh(new THREE.BoxGeometry(TRACK_W - 0.25, 0.2, 0.2), new THREE.MeshBasicMaterial({ color: 0xff1744 }));
                beam.position.set(0, 1.72, z); beam.userData = { type: 'laser', w: TRACK_W - 0.25, h: 0.2, bottomY: 1.62 };
                addEdges(beam, 0xff6688); scene.add(beam); obstacles.push(beam);
                for (const x of [-TRACK_W / 2 + 0.25, TRACK_W / 2 - 0.25]) {
                    const emitter = new THREE.Mesh(new THREE.BoxGeometry(0.22, 0.32, 0.3), new THREE.MeshBasicMaterial({ color: 0xff3355 }));
                    emitter.position.set(x, 1.72, z); emitter.userData = { type: 'laserEmitter', w: 0.22, h: 0.32 };
                    scene.add(emitter); obstacles.push(emitter);
                }
                break;
            }
        }
    }

    function addEdges(mesh, color) {
        const edges = new THREE.LineSegments(new THREE.EdgesGeometry(mesh.geometry), new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.7 }));
        mesh.add(edges);
    }

    function spawnParticles(x, y, z, color, count, spread) {
        for (let i = 0; i < count; i++) {
            const p = new THREE.Mesh(new THREE.SphereGeometry(0.04 + Math.random()*0.04, 4, 4), new THREE.MeshBasicMaterial({ color, transparent: true }));
            p.position.set(x, y, z);
            p.userData = { vx: (Math.random()-0.5) * spread, vy: Math.random() * spread * 0.8, vz: (Math.random()-0.5) * spread, life: 1 };
            scene.add(p); particles.push(p);
        }
    }
    function spawnSpeedLines() {
        if (frame % 3 !== 0) return;
        const line = new THREE.Mesh(new THREE.BoxGeometry(0.02, 0.02, 2 + Math.random()*3), new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.3 }));
        line.position.set((Math.random()-0.5) * 16, Math.random() * 6 + 1, -80);
        line.userData = { isSpeedLine: true }; scene.add(line); particles.push(line);
    }

    function handleKey(e) {
        if (!gameRunning) return;
        if (e.code === 'Space' || e.code === 'KeyW' || e.code === 'ArrowUp') { e.preventDefault(); doJump(); }
        if (e.code === 'KeyS' || e.code === 'ArrowDown') doSlide();
    }
    function endSlide() {
        // 统一结束滑铲:主动起跳和自然结束都走这里。
        if (slideTimer !== null) {
            clearTimeout(slideTimer);
            slideTimer = null;
        }
        isSliding = false;
        camPitchTarget = 0;
    }

    function doJump() {
        if (!gameRunning || isJumping) return;

        // 新功能:允许跳跃主动打断滑铲,不必等待 700ms。
        if (isSliding) endSlide();

        isJumping = true;
        jumpVel = 0.29;
        camPitchTarget = -0.05;
    }

    function doSlide() {
        if (!gameRunning || isJumping || isSliding) return;
        isSliding = true;
        camPitchTarget = 0.08;
        if (slideTimer !== null) clearTimeout(slideTimer);
        slideTimer = setTimeout(() => {
            endSlide();
        }, 700);
    }

    function checkCollisions() {
        const pw = 0.7, ph = isSliding ? 0.7 : 1.5;
        const pBottom = isSliding ? 0 : playerY - 1.6;
        const pTop = pBottom + ph;
        for (let obs of obstacles) {
            if (Math.abs(obs.position.z) > 2) continue;
            let oLeft, oRight, oBottom, oTop;
            if (obs.userData.type === 'laserEmitter') {
                continue;
            } else if (obs.userData.type === 'laser') {
                if (isSliding) continue;
                if (Math.abs(obs.position.z) < 1.2 &&
                    playerX + pw / 2 > obs.position.x - obs.userData.w / 2 &&
                    playerX - pw / 2 < obs.position.x + obs.userData.w / 2) return true;
                continue;
            } else if (obs.userData.type === 'spinning') {
                const angle = obs.rotation.z, hw = obs.userData.w / 2;
                oLeft = obs.position.x - Math.abs(Math.cos(angle)) * hw;
                oRight = obs.position.x + Math.abs(Math.cos(angle)) * hw;
                oBottom = obs.position.y - 0.5; oTop = obs.position.y + 0.5;
            } else {
                oLeft = obs.position.x - obs.userData.w/2;
                oRight = obs.position.x + obs.userData.w/2;
                oBottom = obs.userData.type === 'overhead' ? obs.userData.bottomY : 0;
                oTop = obs.userData.type === 'overhead' ? obs.userData.bottomY + obs.userData.h : obs.userData.h;
            }
            if (playerX + pw/2 > oLeft && playerX - pw/2 < oRight) {
                if (pTop > oBottom && pBottom < oTop && Math.abs(obs.position.z) < 1.2) return true;
            }
            if (Math.abs(obs.position.z) < 2 && Math.abs(obs.position.z) > 0.5 && !obs.userData.nm) {
                const dist = Math.min(Math.abs(playerX - oLeft), Math.abs(playerX - oRight));
                if (dist < 1.8 && dist > pw/2) { obs.userData.nm = true; nearMiss(); }
            }
        }
        return false;
    }

    function nearMiss() {
        score += 50 * (comboCount + 1); comboCount++; comboTimer = 150;
        const nm = document.getElementById('nearMiss');
        nm.textContent = comboCount > 1 ? `NEAR MISS x${comboCount} +${50*comboCount}` : 'NEAR MISS +50';
        nm.classList.remove('show'); void nm.offsetWidth; nm.classList.add('show');
        if (comboCount > 1) {
            const cb = document.getElementById('combo'); cb.textContent = `🔥 x${comboCount} COMBO`;
            cb.classList.remove('show'); void cb.offsetWidth; cb.classList.add('show');
        }
        spawnParticles(playerX, playerY, -2, 0x00ff88, 6, 0.15);
    }

    function startGame() {
        document.getElementById('startScreen').style.display = 'none';
        resetGame(); gameRunning = true;
    }
    function restartGame() {
        document.getElementById('deathScreen').style.display = 'none';
        resetGame(); gameRunning = true;
    }
    function resetGame() {
        // 修复:取消上一局尚未结束的滑铲计时器,防止状态串局。
        endSlide();
        isJumping = false;
        camPitchTarget = 0;
        score = 0; speed = baseSpeed; frame = 0;
        playerX = 0; targetX = 0; playerY = 1.6; jumpVel = 0;
        comboCount = 0; comboTimer = 0; camRoll = 0; camRollVel = 0;
        camPitch = 0; landingImpact = 0; camShakeX = 0; camShakeY = 0;
        currentScene = 'city'; sceneTimer = 0; sceneDuration = 600;
        boostActive = false; boostTimer = 0;
        obstacles.forEach(o => scene.remove(o)); obstacles = [];
        particles.forEach(p => scene.remove(p)); particles = [];
        document.getElementById('boostOverlay').classList.remove('active');
        document.getElementById('speedOverlay').classList.remove('active');
        document.getElementById('combo').classList.remove('show');
        document.getElementById('score').textContent = '0';
    }
    function die() {
        if (!gameRunning) return;
        gameRunning = false;
        endSlide();
        triggerFlash('red'); camShakeX = 1; camShakeY = 1;
        spawnParticles(playerX, playerY, -2, 0xff3333, 20, 0.3);
        if (score > bestScore) bestScore = Math.floor(score);
        setTimeout(() => {
            document.getElementById('deathScreen').style.display = 'flex';
            document.getElementById('finalScore').textContent = Math.floor(score);
            document.getElementById('bestScore').textContent = `BEST: ${bestScore}`;
        }, 600);
    }
    function triggerFlash(type) {
        const f = document.getElementById('flash');
        f.className = 'flash ' + type; void f.offsetWidth; f.classList.add('active');
        setTimeout(() => f.classList.remove('active'), 300);
    }

    function animate() {
        requestAnimationFrame(animate);
        if (gameRunning) {
            frame++;
            const effectiveSpeed = boostActive ? speed * 1.8 : speed;
            speed = Math.min(baseSpeed + frame * 0.00006, maxSpeed);
            score += effectiveSpeed * 0.3;
            sceneTimer++;
            if (sceneTimer > sceneDuration) switchScene();
            if (boostActive) {
                boostTimer--;
                if (boostTimer <= 0) { boostActive = false; document.getElementById('boostOverlay').classList.remove('active'); }
            }
            let moveInput = 0;
            if (keys['ArrowLeft'] || keys['KeyA']) moveInput = -1;
            if (keys['ArrowRight'] || keys['KeyD']) moveInput = 1;
            if (moveInput !== 0) {
                // 新功能:滑铲期间左右移动速度提升至 1.3 倍。
                const moveSpeed = isSliding ? 0.25 * 1.3 : 0.25;
                targetX += moveInput * moveSpeed;
                targetX = Math.max(-TRACK_W/2 + 1, Math.min(TRACK_W/2 - 1, targetX));
            }
            const prevX = playerX;
            playerX += (targetX - playerX) * 0.1;
            const moveVel = playerX - prevX;
            if (isJumping) {
                jumpVel += gravity; playerY += jumpVel;
                if (playerY <= 1.6) {
                    playerY = 1.6; isJumping = false; jumpVel = 0;
                    landingImpact = 0.4; camPitchTarget = 0.03;
                    setTimeout(() => { if (!isSliding) camPitchTarget = 0; }, 100);
                    spawnParticles(playerX, 0.1, -1, 0x00ccff, 4, 0.1);
                }
            }
            camRollTarget = Math.max(-0.12, Math.min(0.12, -moveVel * 8));
            const rollStiffness = 0.08, rollDamping = 0.85;
            camRollVel += (camRollTarget - camRoll) * rollStiffness;
            camRollVel *= rollDamping; camRoll += camRollVel;
            camPitch += (camPitchTarget - camPitch) * 0.1;
            if (landingImpact > 0) {
                camShakeY = landingImpact * (Math.random() - 0.5) * 0.1;
                landingImpact *= 0.85; if (landingImpact < 0.01) landingImpact = 0;
            }
            const speedRatio = (speed - baseSpeed) / (maxSpeed - baseSpeed);
            if (speedRatio > 0.5) {
                camShakeX = (Math.random() - 0.5) * 0.01 * speedRatio;
                camShakeY += (Math.random() - 0.5) * 0.008 * speedRatio;
            }
            if (!isJumping && !isSliding) camBob = Math.sin(frame * 0.18) * 0.025 * (1 + speedRatio);
            else camBob *= 0.9;
            const camY = (isSliding ? 0.8 : playerY) + camBob + camShakeY;
            camera.position.set(playerX + camShakeX, camY, 0);
            camera.rotation.set(camPitch, 0, camRoll);
            camera.lookAt(playerX * 0.6, camY - 0.1 + camPitch * 5, -25);
            camera.rotation.z = camRoll;
            const targetFov = 85 + speedRatio * 20 + (boostActive ? 15 : 0);
            camera.fov += (targetFov - camera.fov) * 0.05; camera.updateProjectionMatrix();
            const rate = Math.max(20, 55 - frame * 0.008);
            if (frame % Math.floor(rate) === 0) spawnObstacle();
            if (speedRatio > 0.3 || boostActive) spawnSpeedLines();
            for (let i = obstacles.length - 1; i >= 0; i--) {
                const o = obstacles[i]; o.position.z += effectiveSpeed;
                if (o.userData.type === 'moving') {
                    o.position.x += o.userData.spd * o.userData.dir;
                    if (Math.abs(o.position.x) > TRACK_W/2 - 2) o.userData.dir *= -1;
                }
                if (o.userData.type === 'spinning') o.rotation.z += o.userData.rotSpeed;
                if (o.position.z > 10) { scene.remove(o); obstacles.splice(i, 1); }
            }
            groundSegs.forEach(s => { s.position.z += effectiveSpeed; if (s.position.z > 10) s.position.z -= 245; });
            envObjects.forEach(o => { o.position.z += effectiveSpeed * 0.7; if (o.position.z > 20) o.position.z -= 250; });
            for (let i = particles.length - 1; i >= 0; i--) {
                const p = particles[i];
                if (p.userData.isSpeedLine) {
                    p.position.z += effectiveSpeed * 3;
                    if (p.position.z > 5) { scene.remove(p); particles.splice(i, 1); }
                } else {
                    p.position.x += p.userData.vx; p.position.y += p.userData.vy; p.position.z += p.userData.vz;
                    p.userData.vy -= 0.005; p.userData.life -= 0.025; p.material.opacity = p.userData.life;
                    if (p.userData.life <= 0) { scene.remove(p); particles.splice(i, 1); }
                }
            }
            if (comboTimer > 0) { comboTimer--; if (comboTimer === 0) comboCount = 0; }
            if (checkCollisions()) die();
            document.getElementById('score').textContent = Math.floor(score);
            document.getElementById('speedFill').style.width = `${speedRatio * 100}%`;
            document.getElementById('speedOverlay').classList.toggle('active', speedRatio > 0.6);
            const tiltNorm = camRoll / 0.12;
            document.getElementById('tiltDot').style.left = `${50 + tiltNorm * 40}%`;
        }
        renderer.render(scene, camera);
    }
    function onResize() {
        camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); renderer.setSize(innerWidth, innerHeight);
    }
    init();
    </script>
<script type="module" src="https://static.cloudflareinsights.com/beacon.min.js/vce701823e78c4301a35b7e07294d87301792088814092" integrity="sha512-UKNk8GbxkABxKcXYuLkO16EleLGUkcvJWtpSNmExE0Too3ZaFAxTscNWEc1OdAv5/BikHawapSCaiD2XCmp+Bw==" data-cf-beacon='{"version":"2024.11.0","token":"7939e04a4baf43c8b86a560f74aac60e","spa":2}' crossorigin="anonymous"></script>
<script type="module" src="https://static.cloudflareinsights.com/beacon.min.js/vce701823e78c4301a35b7e07294d87301792088814092" integrity="sha512-UKNk8GbxkABxKcXYuLkO16EleLGUkcvJWtpSNmExE0Too3ZaFAxTscNWEc1OdAv5/BikHawapSCaiD2XCmp+Bw==" data-cf-beacon='{"version":"2024.11.0","token":"b2074e7888b746fe9fbbc15492b4c3d4","spa":2}' crossorigin="anonymous"></script>
</body>
</html>