MDN wants to talk to developers like you: https://qsurvey.mozilla.com/s3/8d22564490d8

2D 碰撞偵測

翻譯不完整。請協助 翻譯此英文文件

在2D遊戲裡偵測碰撞的演算法決定於碰撞物的幾何形狀 (例如: 矩形對矩形,矩形對圓形,圓形對圓形). 通常你會有個可以包括整個實體的簡單幾何形狀被稱作 "hitbox" 。雖然碰撞表現可能不會是pixel perfect, 但在複數物體時的表現也足夠好了. 這篇文章將會帶你回顧2D遊戲中碰撞偵測最常見的一些方法。

AABB碰撞盒算法 - 軸線對齊盒子

其中一個較簡單的形式是兩個與軸線對齊的矩形的碰撞偵測 — 意味著矩形盒子沒有旋轉.這演算法在確保四邊形成的兩個矩形之間沒有間隙. 有任何間隙意味著碰撞沒有發生.

var rect1 = {x: 5, y: 5, width: 50, height: 50}
var rect2 = {x: 20, y: 10, width: 10, height: 10}

if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.height + rect1.y > rect2.y) {
    // collision detected!
}

// filling in the values =>

if (5 < 30 &&
    55 > 20 &&
    5 < 20 &&
    55 > 10) {
    // collision detected!
}

Note: You can see a live example of Axis-Aligned Bounding Box collision detection on jsFiddle, to illustrate how this code would work in practice.

圓形碰撞

另一個簡單的形式兩個圓形之間的碰撞偵測. 這演算法取兩個圓形的中心點,並確認兩個中心點的距離是否少於兩圓半徑的相加。

var circle1 = {radius: 20, x: 5, y: 5};
var circle2 = {radius: 12, x: 10, y: 5};

var dx = circle1.x - circle2.x;
var dy = circle1.y - circle2.y;
var distance = Math.sqrt(dx * dx + dy * dy);

if (distance < circle1.radius + circle2.radius) {
    // collision detected!
}

注意: 你可以看在jsFiddle上的 live example of Circle collision detection,說明這程式碼是如何實踐的。

分離軸定理

這是個可以偵測任何兩個凸多邊形碰撞的演算法. 這演算法實行起來比起上面兩種更加的複雜但也比較強大. 就像這演算法的複雜性,意味著我們必須考慮性能優化, 將會包含在下一部份.

實作分離軸定理已經超出此頁的範圍, 你可以參考下面推薦的教程:

  1. Separating Axis Theorem (SAT) explanation
  2. Collision detection and response
  3. Collision detection Using the Separating Axis Theorem
  4. SAT (Separating Axis Theorem)
  5. Separation of Axis Theorem (SAT) for Collision Detection

Collision Performance

While some of these algorithms for collision detection are simple enough to calculate, it can be a waste of cycles to test *every* entity with every other entity. Usually games will split collision into two phases, broad and narrow.

Broad Phase

Broad phase should give you a list of entities that *could* be colliding. This can be implemented with a spacial data structure that will give you a rough idea of where the entity exists and what exist around it. Some examples of spacial data structures are Quad Trees, R-Trees or a Spacial Hashmap.

Narrow Phase

When you have a small list of entities to check you will want to use a narrow phase algorithm (like the ones listed above) to provide a certain answer as to whether there is a collision or not.

文件標籤與貢獻者

 此頁面的貢獻者: vintif
 最近更新: vintif,