萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 打飛機遊戲開發全紀錄:遊戲迴圈、碰撞檢測、效能優化、航道系統

專案背景

使用原生 JavaScript 開發一款類似 1942 的垂直捲軸射擊遊戲,相容 IE6+,追求極致效能。

核心架構:遊戲迴圈

為什麼選 setTimeout 而非 setInterval?

特性setIntervalsetTimeout 遞迴
排程機制固定間隔推入隊列上一幀結束後排程下一幀
長幀處理可能導致佇列堆疊、CPU 飆升自動拉長間隔,保護主執行緒
時間精度名義間隔實際間隔 = 設定 + 執行時間
適用場景固定頻率輪詢遊戲迴圈、動畫、不定時任務

高精度遊戲迴圈實作

class GameLoop {
  constructor(targetFPS = 60) {
    this.targetFrameMs = 1000 / targetFPS;
    this.lastTime = performance.now();
    this.running = false;
    this.frameId = null;
  }
  
  start(updateFn) {
    this.running = true;
    this.updateFn = updateFn;
    this.tick();
  }
  
  stop() {
    this.running = false;
    if (this.frameId) cancelAnimationFrame(this.frameId);
  }
  
  tick = () => {
    if (!this.running) return;
    
    const now = performance.now();
    const delta = now - this.lastTime;
    
    // 固定時間步長 (Fixed Timestep) - 物理/邏輯更新
    if (delta >= this.targetFrameMs) {
      this.lastTime = now - (delta % this.targetFrameMs); // 防止時間漂移
      this.updateFn(this.targetFrameMs / 1000); // 傳入秒數
    }
    
    // requestAnimationFrame 用於渲染 (瀏覽器優化)
    this.frameId = requestAnimationFrame(this.tick);
  };
}

// 使用
const gameLoop = new GameLoop(60);
gameLoop.start(dt => {
  updateGame(dt);  // 邏輯更新 (固定 60 FPS)
  renderGame();    // 渲染 (盡可能快,通常鎖螢幕刷新率)
});

遊戲實體系統

// 基礎實體
class Entity {
  constructor(x, y, w, h, speedX = 0, speedY = 0) {
    this.x = x; this.y = y;
    this.w = w; this.h = h;
    this.speedX = speedX; this.speedY = speedY;
    this.active = true;
    this.dom = null; // 對應 DOM 元素
  }
  
  update(dt) {
    this.x += this.speedX * dt;
    this.y += this.speedY * dt;
    this.syncDOM();
  }
  
  syncDOM() {
    if (this.dom) {
      this.dom.style.left = this.x + 'px';
      this.dom.style.top = this.y + 'px';
    }
  }
  
  getRect() {
    return {left: this.x, top: this.y, right: this.x + this.w, bottom: this.y + this.h};
  }
}

// 玩家飛機
class Player extends Entity {
  constructor(canvasW, canvasH) {
    super(canvasW/2 - 20, canvasH - 80, 40, 40);
    this.cooldown = 0;
    this.lives = 3;
  }
  
  update(dt, input) {
    // 鍵盤移動
    if (input.left) this.x -= 300 * dt;
    if (input.right) this.x += 300 * dt;
    if (input.up) this.y -= 300 * dt;
    if (input.down) this.y += 300 * dt;
    
    // 邊界限制
    this.x = Math.max(0, Math.min(this.x, canvasW - this.w));
    this.y = Math.max(0, Math.min(this.y, canvasH - this.h));
    
    // 射擊冷卻
    if (this.cooldown > 0) this.cooldown -= dt;
    if (input.fire && this.cooldown <= 0) {
      this.shoot();
      this.cooldown = 0.15; // 150ms
    }
    
    this.syncDOM();
  }
  
  shoot() {
    // 建立子彈實體,加入遊戲管理器
  }
}

// 敵機
class Enemy extends Entity {
  constructor(x, y, type) {
    const config = Enemy.TYPES[type];
    super(x, y, config.w, config.h, 0, config.speed);
    this.hp = config.hp;
    this.score = config.score;
    this.type = type;
  }
  
  static TYPES = {
    small: {w: 30, h: 30, speed: 150, hp: 1, score: 100},
    medium: {w: 50, h: 50, speed: 100, hp: 3, score: 500},
    large: {w: 80, h: 80, speed: 50, hp: 10, score: 2000}
  };
  
  update(dt) {
    super.update(dt);
    // 超出畫面底部移除
    if (this.y > canvasH) this.active = false;
  }
}

碰撞檢測優化:航道系統

問題

10 敵機 × 20 子彈 = 200 次檢測/幀,IE6 直接卡死。

解決方案:空間分割 - 航道

class LaneSystem {
  constructor(canvasWidth, laneCount, entityWidth) {
    this.laneCount = laneCount;
    this.laneWidth = canvasWidth / laneCount;
    this.entityWidth = entityWidth;
    this.lanes = Array.from({length: laneCount}, () => []);
  }
  
  // 實體進入航道
  assignToLane(entity) {
    const laneIndex = Math.floor(entity.x / this.laneWidth);
    const clamped = Math.max(0, Math.min(laneIndex, this.laneCount - 1));
    entity.lane = clamped;
    this.lanes[clamped].push(entity);
  }
  
  // 實體移除
  removeFromLane(entity) {
    if (entity.lane != null) {
      const idx = this.lanes[entity.lane].indexOf(entity);
      if (idx !== -1) this.lanes[entity.lane].splice(idx, 1);
    }
  }
  
  // 子彈只檢測所在航道的敵機
  getPotentialCollisions(bullet) {
    const laneIndex = Math.floor(bullet.x / this.laneWidth);
    const clamped = Math.max(0, Math.min(laneIndex, this.laneCount - 1));
    return this.lanes[clamped];
  }
  
  // 相鄰航道也檢測 (寬體敵機/子彈)
  getPotentialCollisionsWide(bullet, extraLanes = 1) {
    const laneIndex = Math.floor(bullet.x / this.laneWidth);
    const start = Math.max(0, laneIndex - extraLanes);
    const end = Math.min(this.laneCount - 1, laneIndex + extraLanes);
    const result = [];
    for (let i = start; i <= end; i++) result.push(...this.lanes[i]);
    return result;
  }
}

// 碰撞檢測核心 (AABB - 軸對齊包圍盒)
function checkCollision(a, b) {
  const ra = a.getRect(), rb = b.getRect();
  return !(ra.right < rb.left || ra.left > rb.right || 
           ra.bottom < rb.top || ra.top > rb.bottom);
}

// 遊戲迴圈中的碰撞處理
function processCollisions() {
  // 子彈 vs 敵機
  for (const bullet of bullets) {
    if (!bullet.active) continue;
    const enemies = laneSystem.getPotentialCollisionsWide(bullet, 1);
    for (const enemy of enemies) {
      if (!enemy.active) continue;
      if (checkCollision(bullet, enemy)) {
        bullet.active = false;
        enemy.hp--;
        if (enemy.hp <= 0) {
          enemy.active = false;
          score += enemy.score;
          spawnExplosion(enemy.x, enemy.y);
        }
        break; // 子彈消失,不再檢測其他敵機
      }
    }
  }
  
  // 玩家 vs 敵機 (較少,可全檢測)
  for (const enemy of enemies) {
    if (enemy.active && checkCollision(player, enemy)) {
      playerHit();
      break;
    }
  }
}

視覺效果:DOM vs Canvas

方案優點缺點適用
DOM + CSS無需 Canvas 知識、CSS 動畫、易偵錯大量元素重排重繪慢、IE6 相容好簡單遊戲、教學
Canvas 2D繪圖效能高、像素級控制、無 DOM 開銷需手動管理場景圖、點擊檢測複雜正式遊戲專案
WebGLGPU 加速、大量粒子、特效學習曲線陡峭、Overkill 簡單遊戲大型專案

記憶體管理:物件池

class ObjectPool {
  constructor(createFn, resetFn, initialSize = 10) {
    this.createFn = createFn;
    this.resetFn = resetFn;
    this.pool = [];
    this.active = new Set();
    for (let i = 0; i < initialSize; i++) this.pool.push(createFn());
  }
  
  acquire() {
    let obj = this.pool.pop();
    if (!obj) obj = this.createFn();
    this.resetFn(obj);
    this.active.add(obj);
    return obj;
  }
  
  release(obj) {
    if (this.active.delete(obj)) {
      this.pool.push(obj);
    }
  }
  
  releaseAll() {
    for (const obj of this.active) this.pool.push(obj);
    this.active.clear();
  }
}

// 使用
const bulletPool = new ObjectPool(
  () => new Bullet(0,0),
  b => { b.active = true; b.x = 0; b.y = 0; b.speedY = -600; },
  50
);

// 發射
const bullet = bulletPool.acquire();
bullet.x = player.x + player.w/2 - bullet.w/2;
bullet.y = player.y;

// 回收
function recycleBullets() {
  for (const bullet of bullets) {
    if (!bullet.active || bullet.y < -bullet.h) {
      bulletPool.release(bullet);
    }
  }
}

完整遊戲架構圖


GameApp
├── GameLoop (requestAnimationFrame + Fixed Timestep)
├── InputManager (鍵盤/觸控狀態)
├── EntityManager
│   ├── Player
│   ├── Enemy[] (航道系統管理)
│   ├── Bullet[] (物件池)
│   ├── Effect[] (爆炸、粒子)
│   └── PowerUp[]
├── CollisionSystem (AABB + 航道加速)
├── Renderer (DOM / Canvas)
├── AudioManager (Web Audio API / Audio 元素)
├── StateMachine (Menu → Playing → Paused → GameOver)
└── Storage (LocalStorage 最高分、設定)

IE6 相容性處理

  • 使用 attachEvent / detachEvent 替代 addEventListener
  • 避免 Array.prototype.forEach 等 ES5 方法,改用迴圈
  • requestAnimationFrame Polyfill:setTimeout(fn, 16)
  • performance.now() Polyfill:Date.now()
  • CSS opacity → IE filter: alpha(opacity=50)
  • PNG 透明:AlphaImageLoader filter 或改用 GIF

總結

打飛機遊戲開發核心在於:

  1. 穩定遊戲迴圈:setTimeout 遞迴 + requestAnimationFrame 渲染分離
  2. 空間分割碰撞:航道系統將 O(N×M) 降為 O(N+M)
  3. 物件池:消除 GC 停頓,關鍵針對 IE6
  4. 資料驅動渲染:邏輯與視圖分離,易切換 DOM/Canvas

這些原理延伸至現代遊戲引擎 (Phaser, PixiJS, Cocos, Unity WebGL) 同樣適用。

copyright © 萬盛學電腦網 all rights reserved