HTML5 Canvas 配合高效能 JavaScript 引擎,讓瀏覽器原生運行物理遊戲成為現實。本文以 NTFusion 團隊上架 Chrome Web Store 的《拯救 PAPA》為例,完整拆解 Box2DWeb 物理世界建立、參數調校、DebugDraw 原型驗證、圖片貼圖渲染全流程。
// 1. 建立世界:重力 9.8 m/s²,允許休眠優化
const world = new b2World(new b2Vec2(0, 9.8), true);
const SCALE = 1/30; // 像素 ↔ 米 換算(Box2D 建議 0.1~10 米物體)
// 2. 地面:靜態剛體
const groundBody = world.CreateBody(new b2BodyDef());
const groundFix = new b2FixtureDef();
groundFix.density = 10;
groundFix.friction = 0.3;
groundFix.restitution = 0.1;
groundFix.shape = new b2PolygonShape();
groundFix.shape.SetAsBox(800*SCALE, 20*SCALE); // 半寬、半高
groundBody.CreateFixture(groundFix);
groundBody.SetPosition(new b2Vec2(400*SCALE, 490*SCALE));
// 3. PAPA 方塊:動態剛體
const papaBody = world.CreateBody(new b2BodyDef());
const papaFix = new b2FixtureDef();
papaFix.density = 10; // 密度
papaFix.friction = 0.3; // 摩擦係數
papaFix.restitution = 0.8; // 彈性係數(高彈跳)
papaFix.shape = new b2PolygonShape();
papaFix.shape.SetAsBox(30*SCALE, 30*SCALE);
papaBody.CreateFixture(papaFix);
papaBody.SetType(b2Body.b2_dynamicBody);
papaBody.SetPosition(new b2Vec2(400*SCALE, 100*SCALE));
Box2D 內建 b2DebugDraw 可直接在 Canvas 繪製物理世界輪廓、關節、AABB,無需貼圖即可驗證關卡設計:
const debugDraw = new b2DebugDraw();
debugDraw.SetSprite(document.getElementById('canvas').getContext('2d'));
debugDraw.SetDrawScale(30); // 對應 SCALE 倒數
debugDraw.SetFillAlpha(0.5);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
world.SetDebugDraw(debugDraw);
const TIME_STEP = 1/60; // 固定時間步長
const VEL_ITER = 8, POS_ITER = 3;
function gameLoop() {
// 1. 物理模擬(固定步長,避免幀率波動影響穩定性)
world.Step(TIME_STEP, VEL_ITER, POS_ITER);
world.ClearForces();
// 2. 同步渲染:遍歷所有剛體,根據 position/angle 繪製貼圖
renderBodies();
// 3. 可選:繪製 DebugDraw(開發階段)
// world.DrawDebugData();
requestAnimationFrame(gameLoop);
}
function renderBodies() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let b = world.GetBodyList(); b; b = b.GetNext()) {
if (b.GetType() === b2Body.b2_staticBody) continue; // 地面可單獨繪製背景
const pos = b.GetPosition();
const angle = b.GetAngle();
const userData = b.GetUserData(); // {img: HTMLImageElement, w, h}
ctx.save();
ctx.translate(pos.x / SCALE, pos.y / SCALE); // 米 → 像素
ctx.rotate(angle);
ctx.drawImage(userData.img, -userData.w/2, -userData.h/2, userData.w, userData.h);
ctx.restore();
}
}
核心要訣:物理模擬用米制、固定步長;渲染用像素、變動幀率。兩者透過 SCALE 解耦,確保跨裝置物理行為一致。