使用原生 JavaScript 開發一款類似 1942 的垂直捲軸射擊遊戲,相容 IE6+,追求極致效能。
| 特性 | setInterval | setTimeout 遞迴 |
|---|---|---|
| 排程機制 | 固定間隔推入隊列 | 上一幀結束後排程下一幀 |
| 長幀處理 | 可能導致佇列堆疊、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 + CSS | 無需 Canvas 知識、CSS 動畫、易偵錯 | 大量元素重排重繪慢、IE6 相容好 | 簡單遊戲、教學 |
| Canvas 2D | 繪圖效能高、像素級控制、無 DOM 開銷 | 需手動管理場景圖、點擊檢測複雜 | 正式遊戲專案 |
| WebGL | GPU 加速、大量粒子、特效 | 學習曲線陡峭、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 最高分、設定)
attachEvent / detachEvent 替代 addEventListenerArray.prototype.forEach 等 ES5 方法,改用迴圈requestAnimationFrame Polyfill:setTimeout(fn, 16)performance.now() Polyfill:Date.now()opacity → IE filter: alpha(opacity=50)AlphaImageLoader filter 或改用 GIF打飛機遊戲開發核心在於:
setTimeout 遞迴 + requestAnimationFrame 渲染分離這些原理延伸至現代遊戲引擎 (Phaser, PixiJS, Cocos, Unity WebGL) 同樣適用。