/** * AfriRun - Endless Savannah Runner * Main Game Logic using Three.js * Optimized for mobile with low-poly aesthetics */ class AfriRun { constructor() { this.container = document.getElementById('game-container'); this.canvas = document.getElementById('gameCanvas'); // Game state this.state = 'MENU'; this.score = 0; this.distance = 0; this.speed = 8; this.baseSpeed = 8; this.maxSpeed = 20; this.speedIncrement = 0.0008; // Player properties this.lane = 0; this.targetLane = 0; this.laneWidth = 2.2; this.isJumping = false; this.isSliding = false; this.jumpVelocity = 0; this.gravity = -28; this.jumpForce = 11; this.playerY = 0; this.slideTimer = 0; this.slideDuration = 0.7; this.runCycle = 0; // Obstacles and environment this.obstacles = []; this.decorations = []; this.groundSegments = []; this.segmentLength = 12; this.segmentCount = 6; this.spawnTimer = 0; this.spawnInterval = 1.8; // Object pools for performance this.obstaclePool = []; this.decorationPool = []; // Audio context this.audioContext = null; this.soundEnabled = true; this.drumLoop = null; // Touch handling this.touchStartX = 0; this.touchStartY = 0; this.touchStartTime = 0; // Materials cache this.materials = {}; this.init(); } init() { this.setupScene(); this.setupLights(); this.createMaterials(); this.createPlayer(); this.createGround(); this.setupInputs(); this.setupAudio(); this.resize(); window.addEventListener('resize', () => this.resize()); this.lastTime = performance.now(); requestAnimationFrame((t) => this.gameLoop(t)); } setupScene() { this.scene = new THREE.Scene(); // Warm African sky gradient this.scene.background = new THREE.Color(0xFF9A3C); this.scene.fog = new THREE.Fog(0xFFE4B5, 15, 55); this.camera = new THREE.PerspectiveCamera( 55, window.innerWidth / window.innerHeight, 0.1, 80 ); this.camera.position.set(0, 3.5, 6); this.camera.lookAt(0, 1, -5); this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas, antialias: false, // Disabled for mobile performance alpha: false, powerPreference: "high-performance" }); this.renderer.setSize(window.innerWidth, window.innerHeight); this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = THREE.PCFShadowMap; // Faster than soft this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5)); // Cap for mobile // Create savannah background plane this.createBackground(); } createBackground() { // Distant mountains/hills const hillGeom = new THREE.ConeGeometry(15, 8, 5); const hillMat = new THREE.MeshLambertMaterial({ color: 0xD2691E, flatShading: true }); for (let i = 0; i < 8; i++) { const hill = new THREE.Mesh(hillGeom, hillMat); hill.position.set( (Math.random() - 0.5) * 60, -2, -30 - Math.random() * 20 ); hill.scale.set(1 + Math.random(), 0.5 + Math.random() * 0.5, 1); this.scene.add(hill); } } setupLights() { // Warm ambient light const ambientLight = new THREE.AmbientLight(0xFFD591, 0.5); this.scene.add(ambientLight); // Golden hour sunlight const sunLight = new THREE.DirectionalLight(0xFF8C42, 1.2); sunLight.position.set(-15, 25, -10); sunLight.castShadow = true; sunLight.shadow.mapSize.width = 1024; // Reduced for mobile sunLight.shadow.mapSize.height = 1024; sunLight.shadow.camera.near = 0.5; sunLight.shadow.camera.far = 50; sunLight.shadow.camera.left = -15; sunLight.shadow.camera.right = 15; sunLight.shadow.camera.top = 15; sunLight.shadow.camera.bottom = -10; this.scene.add(sunLight); // Fill light from opposite side const fillLight = new THREE.DirectionalLight(0xFFE4B5, 0.4); fillLight.position.set(10, 10, 5); this.scene.add(fillLight); } createMaterials() { // Cache materials for performance this.materials = { skin: new THREE.MeshLambertMaterial({ color: 0x6B4423, flatShading: true }), shirt: new THREE.MeshLambertMaterial({ color: 0xFF6B35, flatShading: true }), shorts: new THREE.MeshLambertMaterial({ color: 0x2E4057, flatShading: true }), ground: new THREE.MeshLambertMaterial({ color: 0xC49420, flatShading: true }), rock: new THREE.MeshLambertMaterial({ color: 0x8B7355, flatShading: true }), wood: new THREE.MeshLambertMaterial({ color: 0x5D4E37, flatShading: true }), grass: new THREE.MeshLambertMaterial({ color: 0x7FA858, flatShading: true }), acaciaTrunk: new THREE.MeshLambertMaterial({ color: 0x4A3728, flatShading: true }), acaciaLeaves: new THREE.MeshLambertMaterial({ color: 0x6B8E23, flatShading: true }), hutWall: new THREE.MeshLambertMaterial({ color: 0xD4A574, flatShading: true }), hutRoof: new THREE.MeshLambertMaterial({ color: 0x8B4513, flatShading: true }), bridge: new THREE.MeshLambertMaterial({ color: 0xA0522D, flatShading: true }) }; } createPlayer() { this.playerGroup = new THREE.Group(); // Low-poly African runner // Head const headGeom = new THREE.BoxGeometry(0.35, 0.4, 0.35); const head = new THREE.Mesh(headGeom, this.materials.skin); head.position.y = 1.6; head.castShadow = true; this.playerGroup.add(head); // Body - tank top style const bodyGeom = new THREE.BoxGeometry(0.5, 0.7, 0.3); const body = new THREE.Mesh(bodyGeom, this.materials.shirt); body.position.y = 1.05; body.castShadow = true; this.playerGroup.add(body); // Arms const armGeom = new THREE.BoxGeometry(0.12, 0.7, 0.12); this.leftArm = new THREE.Mesh(armGeom, this.materials.skin); this.leftArm.position.set(-0.35, 1.1, 0); this.leftArm.castShadow = true; this.playerGroup.add(this.leftArm); this.rightArm = new THREE.Mesh(armGeom, this.materials.skin); this.rightArm.position.set(0.35, 1.1, 0); this.rightArm.castShadow = true; this.playerGroup.add(this.rightArm); // Legs/Shorts const legGeom = new THREE.BoxGeometry(0.15, 0.8, 0.15); const shortLegGeom = new THREE.BoxGeometry(0.18, 0.3, 0.18); // Left leg this.leftLegGroup = new THREE.Group(); const leftShort = new THREE.Mesh(shortLegGeom, this.materials.shorts); leftShort.position.y = 0.6; leftShort.castShadow = true; const leftLegLower = new THREE.Mesh(legGeom, this.materials.skin); leftLegLower.position.y = 0.2; leftLegLower.castShadow = true; this.leftLegGroup.add(leftShort); this.leftLegGroup.add(leftLegLower); this.leftLegGroup.position.set(-0.15, 0, 0); this.playerGroup.add(this.leftLegGroup); // Right leg this.rightLegGroup = new THREE.Group(); const rightShort = new THREE.Mesh(shortLegGeom, this.materials.shorts); rightShort.position.y = 0.6; rightShort.castShadow = true; const rightLegLower = new THREE.Mesh(legGeom, this.materials.skin); rightLegLower.position.y = 0.2; rightLegLower.castShadow = true; this.rightLegGroup.add(rightShort); this.rightLegGroup.add(rightLegLower); this.rightLegGroup.position.set(0.15, 0, 0); this.playerGroup.add(this.rightLegGroup); this.scene.add(this.playerGroup); } createGround() { // Create dirt path segments with savannah grass borders for (let i = 0; i < this.segmentCount; i++) { const segmentGroup = new THREE.Group(); // Dirt path const pathGeom = new THREE.PlaneGeometry(6, this.segmentLength, 3, 3); const path = new THREE.Mesh(pathGeom, this.materials.ground); path.rotation.x = -Math.PI / 2; path.position.y = 0; path.receiveShadow = true; // Add slight unevenness const positions = path.geometry.attributes.position; for (let j = 0; j < positions.count; j++) { const z = positions.getZ(j); positions.setZ(j, z + (Math.random() - 0.5) * 0.15); } // Grass borders const grassGeom = new THREE.PlaneGeometry(4, this.segmentLength, 2, 3); const leftGrass = new THREE.Mesh(grassGeom, this.materials.grass); leftGrass.rotation.x = -Math.PI / 2; leftGrass.position.set(-5, 0.02, 0); leftGrass.receiveShadow = true; const rightGrass = new THREE.Mesh(grassGeom, this.materials.grass); rightGrass.rotation.x = -Math.PI / 2; rightGrass.position.set(5, 0.02, 0); rightGrass.receiveShadow = true; segmentGroup.add(path); segmentGroup.add(leftGrass); segmentGroup.add(rightGrass); segmentGroup.position.z = -i * this.segmentLength; this.scene.add(segmentGroup); this.groundSegments.push({ group: segmentGroup, index: i, hasDecorations: false }); } } createAcaciaTree() { const group = new THREE.Group(); // Trunk - curved slightly const trunkGeom = new THREE.CylinderGeometry(0.15, 0.25, 2.5, 5); const trunk = new THREE.Mesh(trunkGeom, this.materials.acaciaTrunk); trunk.position.y = 1.25; trunk.castShadow = true; group.add(trunk); // Branches going up then flat top const branch1Geom = new THREE.CylinderGeometry(0.1, 0.15, 1.5, 4); const branch1 = new THREE.Mesh(branch1Geom, this.materials.acaciaTrunk); branch1.position.set(0.4, 2.2, 0); branch1.rotation.z = -0.5; group.add(branch1); const branch2Geom = new THREE.CylinderGeometry(0.1, 0.15, 1.5, 4); const branch2 = new THREE.Mesh(branch2Geom, this.materials.acaciaTrunk); branch2.position.set(-0.4, 2.2, 0); branch2.rotation.z = 0.5; group.add(branch2); // Flat top (acacia characteristic) const topGeom = new THREE.CylinderGeometry(1.8, 0.3, 0.4, 6); const top = new THREE.Mesh(topGeom, this.materials.acaciaLeaves); top.position.y = 2.8; top.castShadow = true; group.add(top); return group; } createAfricanHut() { const group = new THREE.Group(); // Round hut base const baseGeom = new THREE.CylinderGeometry(1.2, 1.3, 1.2, 6); const base = new THREE.Mesh(baseGeom, this.materials.hutWall); base.position.y = 0.6; base.castShadow = true; group.add(base); // Conical thatched roof const roofGeom = new THREE.ConeGeometry(1.6, 1.2, 6); const roof = new THREE.Mesh(roofGeom, this.materials.hutRoof); roof.position.y = 1.8; roof.castShadow = true; group.add(roof); // Door const doorGeom = new THREE.PlaneGeometry(0.4, 0.6); const doorMat = new THREE.MeshLambertMaterial({ color: 0x2F1810 }); const door = new THREE.Mesh(doorGeom, doorMat); door.position.set(0, 0.3, 1.31); group.add(door); return group; } spawnObstacle(zPosition) { const lane = Math.floor(Math.random() * 3) - 1; const rand = Math.random(); let obstacle; if (rand < 0.25) { // Rock obstacle - must dodge const geom = new THREE.DodecahedronGeometry(0.5, 0); obstacle = new THREE.Mesh(geom, this.materials.rock); obstacle.position.set(lane * this.laneWidth, 0.25, zPosition); obstacle.castShadow = true; obstacle.userData = { type: 'rock', lane: lane, speedPenalty: 0 }; } else if (rand < 0.5) { // Fallen tree - must jump const geom = new THREE.BoxGeometry(2, 0.3, 0.3); obstacle = new THREE.Mesh(geom, this.materials.wood); obstacle.position.set(lane * this.laneWidth, 0.2, zPosition); obstacle.castShadow = true; obstacle.userData = { type: 'log', lane: lane, speedPenalty: 0 }; } else if (rand < 0.7) { // Gap with bridge or just gap if (Math.random() > 0.5) { // Bridge const geom = new THREE.BoxGeometry(2, 0.2, 3); obstacle = new THREE.Mesh(geom, this.materials.bridge); obstacle.position.set(lane * this.laneWidth, 0.1, zPosition); obstacle.castShadow = true; obstacle.userData = { type: 'bridge', lane: lane, speedPenalty: 0 }; } else { // Actual gap - player must jump over obstacle = new THREE.Group(); obstacle.position.set(lane * this.laneWidth, 0, zPosition); obstacle.userData = { type: 'gap', lane: lane, speedPenalty: 0, width: 2 }; } } else { // Tall grass - slows player const geom = new THREE.ConeGeometry(0.4, 1.2, 4); obstacle = new THREE.Mesh(geom, this.materials.grass); obstacle.position.set(lane * this.laneWidth, 0.6, zPosition); obstacle.userData = { type: 'grass', lane: lane, speedPenalty: 0.5 }; // Slows down } this.scene.add(obstacle); this.obstacles.push(obstacle); } spawnDecoration(zPosition) { // Spawn acacia trees and huts const count = 1 + Math.floor(Math.random() * 2); for (let i = 0; i < count; i++) { const side = Math.random() > 0.5 ? 1 : -1; const distance = 4 + Math.random() * 8; const x = side * distance; let decor; const rand = Math.random(); if (rand < 0.6) { // Acacia tree decor = this.createAcaciaTree(); } else if (rand < 0.85) { // African hut decor = this.createAfricanHut(); } else { // Rock/bush const geom = new THREE.DodecahedronGeometry(0.3 + Math.random() * 0.3, 0); decor = new THREE.Mesh(geom, this.materials.rock); } decor.position.set(x, 0, zPosition + (Math.random() - 0.5) * 5); // Random scale const scale = 0.8 + Math.random() * 0.4; decor.scale.set(scale, scale, scale); this.scene.add(decor); this.decorations.push(decor); } } setupInputs() { document.addEventListener('keydown', (e) => this.handleKeyDown(e)); // Touch areas for mobile const touchLeft = document.getElementById('touch-left'); const touchJump = document.getElementById('touch-jump'); const touchRight = document.getElementById('touch-right'); if (touchLeft) { touchLeft.addEventListener('touchstart', (e) => { e.preventDefault(); this.moveLane(-1); touchLeft.classList.add('touch-active'); setTimeout(() => touchLeft.classList.remove('touch-active'), 100); }); } if (touchRight) { touchRight.addEventListener('touchstart', (e) => { e.preventDefault(); this.moveLane(1); touchRight.classList.add('touch-active'); setTimeout(() => touchRight.classList.remove('touch-active'), 100); }); } if (touchJump) { touchJump.addEventListener('touchstart', (e) => { e.preventDefault(); if (this.isJumping) { this.slide(); } else { this.jump(); } touchJump.classList.add('touch-active'); setTimeout(() => touchJump.classList.remove('touch-active'), 100); }); } // UI Buttons document.getElementById('menu').addEventListener('start-game', () => { this.startGame(); }); document.getElementById('menu').addEventListener('restart-game', () => { this.resetGame(); this.startGame(); }); document.getElementById('menu').addEventListener('toggle-sound', (e) => { this.soundEnabled = e.detail.enabled; if (this.soundEnabled && this.state === 'PLAYING') { this.startDrumBeat(); } else { this.stopDrumBeat(); } }); } handleKeyDown(e) { if (this.state !== 'PLAYING') return; switch(e.code) { case 'Space': case 'ArrowUp': e.preventDefault(); this.jump(); break; case 'KeyS': case 'ArrowDown': e.preventDefault(); this.slide(); break; case 'ArrowLeft': case 'KeyA': e.preventDefault(); this.moveLane(-1); break; case 'ArrowRight': case 'KeyD': e.preventDefault(); this.moveLane(1); break; } } moveLane(direction) { this.targetLane = Math.max(-1, Math.min(1, this.targetLane + direction)); this.playSound('step'); } jump() { if (!this.isJumping && !this.isSliding) { this.isJumping = true; this.jumpVelocity = this.jumpForce; this.playSound('jump'); } } slide() { if (!this.isJumping && !this.isSliding) { this.isSliding = true; this.slideTimer = this.slideDuration; this.playSound('slide'); // Visual slide - scale down this.playerGroup.scale.y = 0.5; this.playerGroup.position.y = -0.5; } } setupAudio() { try { this.audioContext = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) { console.warn('Audio not supported'); } } playSound(type) { if (!this.soundEnabled || !this.audioContext) return; const osc = this.audioContext.createOscillator(); const gain = this.audioContext.createGain(); switch(type) { case 'jump': osc.frequency.setValueAtTime(300, this.audioContext.currentTime); osc.frequency.exponentialRampToValueAtTime(600, this.audioContext.currentTime + 0.1); gain.gain.setValueAtTime(0.3, this.audioContext.currentTime); gain.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + 0.1); break; case 'slide': osc.frequency.setValueAtTime(200, this.audioContext.currentTime); osc.frequency.linearRampToValueAtTime(100, this.audioContext.currentTime + 0.2); gain.gain.setValueAtTime(0.3, this.audioContext.currentTime); gain.gain.linearRampToValueAtTime(0.01, this.audioContext.currentTime + 0.2); break; case 'step': osc.frequency.setValueAtTime(150, this.audioContext.currentTime); gain.gain.setValueAtTime(0.1, this.audioContext.currentTime); gain.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + 0.05); break; case 'drum': // Low drum beat osc.frequency.setValueAtTime(80, this.audioContext.currentTime); osc.frequency.exponentialRampToValueAtTime(40, this.audioContext.currentTime + 0.15); gain.gain.setValueAtTime(0.4, this.audioContext.currentTime); gain.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + 0.15); break; case 'crash': // Noise for collision const bufferSize = this.audioContext.sampleRate * 0.5; const buffer = this.audioContext.createBuffer(1, bufferSize, this.audioContext.sampleRate); const data = buffer.getChannelData(0); for (let i = 0; i < bufferSize; i++) { data[i] = Math.random() * 2 - 1; } const noise = this.audioContext.createBufferSource(); noise.buffer = buffer; const noiseGain = this.audioContext.createGain(); noiseGain.gain.setValueAtTime(0.5, this.audioContext.currentTime); noiseGain.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + 0.3); noise.connect(noiseGain); noiseGain.connect(this.audioContext.destination); noise.start(); return; } osc.connect(gain); gain.connect(this.audioContext.destination); osc.start(); osc.stop(this.audioContext.currentTime + 0.5); } startDrumBeat() { if (this.drumLoop) clearInterval(this.drumLoop); this.drumLoop = setInterval(() => { this.playSound('drum'); }, 500); } stopDrumBeat() { if (this.drumLoop) { clearInterval(this.drumLoop); this.drumLoop = null; } } startGame() { this.state = 'PLAYING'; this.score = 0; this.distance = 0; this.speed = this.baseSpeed; // Resume audio context if suspended if (this.audioContext && this.audioContext.state === 'suspended') { this.audioContext.resume(); } if (this.soundEnabled) this.startDrumBeat(); // Update UI document.getElementById('menu').hide(); document.getElementById('hud').updateScore(0); document.getElementById('hud').show(); } gameOver() { this.state = 'GAMEOVER'; this.stopDrumBeat(); this.playSound('crash'); // Update UI document.getElementById('hud').hide(); document.getElementById('menu').showGameOver(Math.floor(this.score)); } resetGame() { // Clear obstacles this.obstacles.forEach(obj => this.scene.remove(obj)); this.obstacles = []; this.decorations.forEach(obj => this.scene.remove(obj)); this.decorations = []; // Reset player this.lane = 0; this.targetLane = 0; this.runCycle = 0; this.playerGroup.position.set(0, 0, 0); this.playerGroup.scale.set(1, 1, 1); this.playerGroup.rotation.set(0, 0, 0); this.isJumping = false; this.isSliding = false; this.jumpVelocity = 0; // Reset limbs this.leftArm.rotation.x = 0; this.rightArm.rotation.x = 0; this.leftLegGroup.rotation.x = 0; this.rightLegGroup.rotation.x = 0; // Reset ground this.groundSegments.forEach((seg, i) => { seg.group.position.z = -i * this.segmentLength; seg.hasDecorations = false; }); this.spawnTimer = 0; this.speed = this.baseSpeed; } checkCollisions() { const playerZ = this.playerGroup.position.z; const playerX = this.playerGroup.position.x; const playerY = this.playerGroup.position.y; for (let obstacle of this.obstacles) { if (!obstacle.position) continue; const zDiff = obstacle.position.z - playerZ; if (Math.abs(zDiff) < 0.6) { const lane = obstacle.userData.lane * this.laneWidth; if (Math.abs(playerX - lane) < 0.7) { const type = obstacle.userData.type; if (type === 'rock') { // Must dodge - rocks are too tall if (playerY < 0.8) { this.gameOver(); return; } } else if (type === 'log') { // Must jump if (!this.isJumping && playerY < 0.4) { this.gameOver(); return; } } else if (type === 'gap') { // Must jump over gap if (!this.isJumping && playerY < 0.2) { this.gameOver(); return; } } // Bridge and grass don't cause game over } } } } update(delta) { if (this.state !== 'PLAYING') { // Idle breathing animation const time = performance.now() * 0.002; this.playerGroup.position.y = Math.sin(time) * 0.03; this.playerGroup.rotation.y = Math.sin(time * 0.5) * 0.05; return; } // Increase speed gradually this.speed = Math.min(this.maxSpeed, this.speed + this.speedIncrement); // Update distance and score this.distance += this.speed * delta; this.score = this.distance * 10; document.getElementById('hud').updateScore(Math.floor(this.score)); // Lane changing (smooth lerp) this.lane += (this.targetLane - this.lane) * 8 * delta; this.playerGroup.position.x = this.lane * this.laneWidth; // Jump physics if (this.isJumping) { this.jumpVelocity += this.gravity * delta; this.playerY += this.jumpVelocity * delta; if (this.playerY <= 0) { this.playerY = 0; this.isJumping = false; this.jumpVelocity = 0; // Landing impact this.playerGroup.scale.y = 0.9; setTimeout(() => { if (!this.isSliding) this.playerGroup.scale.y = 1; }, 100); } this.playerGroup.position.y = this.playerY; // Forward lean while jumping this.playerGroup.rotation.x = Math.min(0.3, -this.jumpVelocity * 0.02); } else { // Running bob const bob = Math.sin(performance.now() * 0.015) * 0.03; this.playerGroup.position.y = this.isSliding ? 0.3 : bob; this.playerGroup.rotation.x = 0; } // Slide timer and animation if (this.isSliding) { this.slideTimer -= delta; // Smooth slide transition const slideProgress = 1 - (this.slideTimer / this.slideDuration); this.playerGroup.scale.y = 0.5 + (1 - slideProgress) * 0.5; this.playerGroup.position.y = 0.3; if (this.slideTimer <= 0) { this.isSliding = false; this.playerGroup.scale.y = 1; this.playerGroup.position.y = this.isJumping ? this.playerY : 0; } } // Animate limbs with run cycle this.runCycle += delta * 10 * (this.speed / this.baseSpeed); if (!this.isJumping && !this.isSliding) { // Arms pumping this.leftArm.rotation.x = Math.sin(this.runCycle) * 0.8; this.rightArm.rotation.x = Math.sin(this.runCycle + Math.PI) * 0.8; // Legs running const legSwing = 0.7; this.leftLegGroup.rotation.x = Math.sin(this.runCycle + Math.PI) * legSwing; this.rightLegGroup.rotation.x = Math.sin(this.runCycle) * legSwing; // Bend knees when lifting const leftBend = Math.max(0, Math.sin(this.runCycle + Math.PI)); const rightBend = Math.max(0, Math.sin(this.runCycle)); } else if (this.isJumping) { // Arms up when jumping this.leftArm.rotation.x = -1.5; this.rightArm.rotation.x = -1.5; // Legs tucked this.leftLegGroup.rotation.x = -0.5; this.rightLegGroup.rotation.x = 0.5; } else if (this.isSliding) { // Arms forward when sliding this.leftArm.rotation.x = -1; this.rightArm.rotation.x = -1; } // Move ground segments (endless scroll) this.groundSegments.forEach(segment => { segment.group.position.z += this.speed * delta; if (segment.group.position.z > 5) { segment.group.position.z -= this.segmentCount * this.segmentLength; segment.hasDecorations = false; } if (segment.group.position.z < -10 && !segment.hasDecorations) { segment.hasDecorations = true; this.spawnDecoration(segment.group.position.z); } }); // Move and spawn obstacles this.spawnTimer -= delta * (this.speed / this.baseSpeed); if (this.spawnTimer <= 0) { this.spawnObstacle(-50); this.spawnTimer = this.spawnInterval * (0.8 + Math.random() * 0.4); } for (let i = this.obstacles.length - 1; i >= 0; i--) { const obs = this.obstacles[i]; if (obs.position) { obs.position.z += this.speed * delta; // Check if in tall grass if (obs.userData.type === 'grass' && Math.abs(obs.position.z - this.playerGroup.position.z) < 1) { if (Math.abs(this.playerGroup.position.x - obs.position.x) < 0.8) { this.speed = Math.max(this.baseSpeed, this.speed - obs.userData.speedPenalty); } } if (obs.position.z > 10) { this.scene.remove(obs); this.obstacles.splice(i, 1); } } } // Move decorations for (let i = this.decorations.length - 1; i >= 0; i--) { const decor = this.decorations[i]; decor.position.z += this.speed * delta; if (decor.position.z > 20) { this.scene.remove(decor); this.decorations.splice(i, 1); } } // Smooth camera follow const targetCamX = this.playerGroup.position.x * 0.4; this.camera.position.x += (targetCamX - this.camera.position.x) * 3 * delta; // Camera tilt for depth this.camera.rotation.z = (this.playerGroup.position.x * 0.1) * delta; this.checkCollisions(); } gameLoop(currentTime) { const delta = Math.min((currentTime - this.lastTime) / 1000, 0.1); // Cap delta this.lastTime = currentTime; this.update(delta); this.renderer.render(this.scene, this.camera); requestAnimationFrame((t) => this.gameLoop(t)); } resize() { const width = window.innerWidth; const height = window.innerHeight; this.camera.aspect = width / height; this.camera.updateProjectionMatrix(); this.renderer.setSize(width, height); } }