多邊形碰撞檢測 -- 分離軸算法

多邊形碰撞檢測在游戲開發(fā)中是非常常用的算法倦西,最直接的算法是檢測兩個多邊形的每個點是否被包含翎冲,但是由于多邊形的數(shù)量和多邊形點的數(shù)量導致這種最直接的算法的效率非常之低迈套。本文將介紹一個非常簡單并且效率極高的算法——“分離軸算法”,并用C語言和Lua語言分別實現(xiàn)該算法亥至,可以分別用于Cocos2d和Corona開發(fā)兆览。

分離軸算法

圖片
圖片

上圖就是分離軸算法的圖示屈溉,首先需要知道分離軸算法只適用于“凸多邊形”,但是由于“凹多邊形”可以分成多個凸多邊形組成抬探,所以該算法可以用于所有多邊形碰撞檢測子巾。不知道凹多邊形是什么的看下圖:


圖片
圖片

凹多邊形就是含有頂點的內(nèi)角度超過180°的多邊形,反之就是凸多邊形。

簡單的說线梗,分離軸算法就是指兩個多邊形能有一條直線將彼此分開椰于,如圖中黑線“Seperating line”,而與之垂直的綠線就是分離軸“Separating axis”仪搔。圖中虛線表示的是多邊形在分離軸上的投影(Projection)瘾婿。詳細的數(shù)學理論請查看wiki,我這里只講該算法的實現(xiàn)方式僻造。如果用偽代碼來表示就是:

bool sat(polygon a, polygon b){
    for (int i = 0; i < a.edges.length; i++){
        vector axis = a.edges[i].direction; // Get the direction vector of the edge
        axis = vec_normal(axis); // We need to find the normal of the axis vector.
        axis = vec_unit(axis); // We also need to "normalize" this vector, or make its length/magnitude equal to 1
 
        // Find the projection of the two polygons onto the axis
        segment proj_a = project(a, axis), proj_b = project(b, axis); 
 
        if(!seg_overlap(proj_a, proj_b)) return false; // If they do not overlap, then return false
    }
    ... // Same thing for polygon b
    // At this point, we know that there were always intersections, hence the two polygons must be colliding
    return true;
}

首先取多邊形a的一邊憋他,得出該邊的法線(即分離軸)。然后算出兩個多邊形在該法線上的投影髓削,如果兩個投影沒有重疊則說明兩個多邊形不相交。遍歷多邊形a所有的邊镀娶,如果所有法線都不滿足條件立膛,則說明兩多邊形相交。

算法實現(xiàn)

首先我們需要定義幾個數(shù)據(jù)類型和函數(shù)梯码。
Lua:

function vec(x, y)
    return {x, y}
end
 
v = vec -- shortcut
 
function dot(v1, v2)
    return v1[1]*v2[1] + v1[2]*v2[2]
end
 
function normalize(v)
    local mag = math.sqrt(v[1]^2 + v[2]^2)
    return vec(v[1]/mag, v[2]/mag)
end
 
function perp(v)
    return {v[2],-v[1]}
end
 
function segment(a, b)
    local obj = {a=a, b=b, dir={b[1] - a[1], b[2] - a[2]}}
    obj[1] = obj.dir[1]; obj[2] = obj.dir[2]
    return obj
end
 
function polygon(vertices)
    local obj = {}
    obj.vertices = vertices
    obj.edges = {}
    for i=1,#vertices do
        table.insert(obj.edges, segment(vertices[i], vertices[1+i%(#vertices)]))
    end
    return obj
end

vec為矢量或者向量宝泵,也可表示點;dot為矢量點投影運算轩娶;normalize為求模運算儿奶;perp計算法線向量;segment表示線段鳄抒;polygon為多邊形闯捎,包括頂點vertices和邊edges,所有點的順序必須按順時針或者逆時針许溅。如:

a = polygon{v(0,0),v(0,1),v(1,1),v(1,0)}

下面是C語言版的:

typedef struct {float x, y;} vec;
 
vec v(float x, float y){
    vec a = {x, y}; // shorthand for declaration
    return a;
}
 
float dot(vec a, vec b){
    return a.x*b.x+a.y*b.y;
}
 
#include <math.h>
vec normalize(vec v){
    float mag = sqrt(v.x*v.x + v.y*v.y);
    vec b = {v.x/mag, v.y/mag}; // vector b is only of distance 1 from the origin
    return b;
}
 
vec perp(vec v){
    vec b = {v.y, -v.x};
    return b;
}
 
typedef struct {vec p0, p1, dir;} seg;
 
seg segment(vec p0, vec p1){
    vec dir = {p1.x-p0.x, p1.y-p0.y};
    seg s = {p0, p1, dir};
    return s;
}
 
typedef struct {int n; vec *vertices; seg *edges;} polygon; // Assumption: Simply connected => chain vertices together
 
polygon new_polygon(int nvertices, vec *vertices){
    seg *edges = (seg*)malloc(sizeof(seg)*(nvertices));
    int i;
    for (i = 0; i < nvertices-1; i++){
        vec dir = {vertices[i+1].x-vertices[i].x, vertices[i+1].y-vertices[i].y};seg cur = {vertices[i], vertices[i+1], dir}; // We can also use the segment method here, but this is more explicit
        edges[i] = cur;
    }
    vec dir = {vertices[0].x-vertices[nvertices-1].x, vertices[0].y-vertices[nvertices-1].y};seg cur = {vertices[nvertices-1], vertices[0], dir};
    edges[nvertices-1] = cur; // The last edge is between the first vertex and the last vertex
    polygon shape = {nvertices, vertices, edges};
    return shape;
}
 
polygon Polygon(int nvertices, ...){
    va_list args;
    va_start(args, nvertices);
    vec *vertices = (vec*)malloc(sizeof(vec)*nvertices);
    int i;
    for (i = 0; i < nvertices; i++){
        vertices[i] = va_arg(args, vec);
    }
    va_end(args);
    return new_polygon(nvertices, vertices);
}

有了數(shù)據(jù)類型然后就是算法的判斷函數(shù)瓤鼻。
Lua:

-- We keep a running range (min and max) values of the projection, and then use that as our shadow
 
function project(a, axis)
    axis = normalize(axis)
    local min = dot(a.vertices[1],axis)
    local max = min
    for i,v in ipairs(a.vertices) do
        local proj =  dot(v, axis) -- projection
        if proj < min then min = proj end
        if proj > max then max = proj end
    end
 
    return {min, max}
end
 
function contains(n, range)
    local a, b = range[1], range[2]
    if b < a then a = b; b = range[1] end
    return n >= a and n <= b
end
 
function overlap(a_, b_)
    if contains(a_[1], b_) then return true
    elseif contains(a_[2], b_) then return true
    elseif contains(b_[1], a_) then return true
    elseif contains(b_[2], a_) then return true
    end
    return false
end

project為計算投影函數(shù),先計算所有邊長的投影贤重,然后算出投影的最大和最小點即起始點茬祷;overlap函數(shù)判斷兩條線段是否重合。
C:

float* project(polygon a, vec axis){
    axis = normalize(axis);
    int i;
    float min = dot(a.vertices[0],axis); float max = min; // min and max are the start and finish points
    for (i=0;i<a.n;i++){
        float proj = dot(a.vertices[i],axis); // find the projection of every point on the polygon onto the line.
        if (proj < min) min = proj; if (proj > max) max = proj;
    }
    float* arr = (float*)malloc(2*sizeof(float));
    arr[0] = min; arr[1] = max;
    return arr;
}
 
int contains(float n, float* range){
    float a = range[0], b = range[1];
    if (b<a) {a = b; b = range[0];}
    return (n >= a && n <= b);
}
 
int overlap(float* a_, float* b_){
    if (contains(a_[0],b_)) return 1;
    if (contains(a_[1],b_)) return 1;
    if (contains(b_[0],a_)) return 1;
    if (contains(b_[1],a_)) return 1;
    return 0;
}

最后是算法實現(xiàn)函數(shù)并蝗,使用到上面的數(shù)據(jù)和函數(shù)祭犯。
Lua:

function sat(a, b)
    for i,v in ipairs(a.edges) do
        local axis = perp(v)
        local a_, b_ = project(a, axis), project(b, axis)
        if not overlap(a_, b_) then return false end
    end
    for i,v in ipairs(b.edges) do
        local axis = perp(v)
        local a_, b_ = project(a, axis), project(b, axis)
        if not overlap(a_, b_) then return false end
    end
 
    return true
end

遍歷a和b兩個多邊形的所有邊長,判斷投影是否重合滚停。
C:

int sat(polygon a, polygon b){
    int i;
    for (i=0;i<a.n;i++){
        vec axis = a.edges[i].dir; // Get the direction vector
        axis = perp(axis); // Get the normal of the vector (90 degrees)
        float *a_ = project(a,axis), *b_ = project(b,axis); // Find the projection of a and b onto axis
        if (!overlap(a_,b_)) return 0; // If they do not overlap, then no collision
    }
 
    for (i=0;i<b.n;i++){ // repeat for b
        vec axis = b.edges[i].dir;
        axis = perp(axis);
        float *a_ = project(a,axis), *b_ = project(b,axis);
        if (!overlap(a_,b_)) return 0;
    }
    return 1;
}

兩個函數(shù)的使用方法很簡單沃粗,只要定義好了多邊形就行了。
Lua:

a = polygon{v(0,0),v(0,5),v(5,4),v(3,0)}
b = polygon{v(4,4),v(4,6),v(6,6),v(6,4)}
 
print(sat(a,b)) -- true

C:

polygon a = Polygon(4, v(0,0),v(0,3),v(3,3),v(3,0)), b = Polygon(4, v(4,4),v(4,6),v(6,6),v(6,4));
printf("%d\n", sat(a,b)); // false
 
a = Polygon(4, v(0,0),v(0,5),v(5,4),v(3,0));  b = Polygon(4, v(4,4),v(4,6),v(6,6),v(6,4));
printf("%d\n", sat(a,b)); // true

完整的函數(shù)下載:Lua铐刘、C

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末陪每,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌檩禾,老刑警劉巖挂签,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異盼产,居然都是意外死亡饵婆,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門戏售,熙熙樓的掌柜王于貴愁眉苦臉地迎上來懊直,“玉大人,你說我怎么就攤上這事柒瓣“缃常” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵锋喜,是天一觀的道長些己。 經(jīng)常有香客問我,道長嘿般,這世上最難降的妖魔是什么段标? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮炉奴,結果婚禮上逼庞,老公的妹妹穿的比我還像新娘。我一直安慰自己瞻赶,他們只是感情好赛糟,可當我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著共耍,像睡著了一般虑灰。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上痹兜,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天穆咐,我揣著相機與錄音,去河邊找鬼字旭。 笑死对湃,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的遗淳。 我是一名探鬼主播拍柒,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼屈暗!你這毒婦竟也來了拆讯?” 一聲冷哼從身側(cè)響起脂男,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎种呐,沒想到半個月后宰翅,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡爽室,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年汁讼,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片阔墩。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡嘿架,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出啸箫,到底是詐尸還是另有隱情耸彪,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布忘苛,位于F島的核電站搜囱,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏柑土。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一绊汹、第九天 我趴在偏房一處隱蔽的房頂上張望稽屏。 院中可真熱鬧,春花似錦西乖、人聲如沸狐榔。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽薄腻。三九已至,卻和暖如春届案,著一層夾襖步出監(jiān)牢的瞬間庵楷,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工楣颠, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留尽纽,地道東北人。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓童漩,卻偏偏與公主長得像弄贿,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子矫膨,可洞房花燭夜當晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Lua 5.1 參考手冊 by Roberto Ierusalimschy, Luiz Henrique de F...
    蘇黎九歌閱讀 13,791評論 0 38
  • 前言 多邊形偏移 (polygon offset) 算法可能我們印象不深差凹,不過用過 autoCAD 的同學應該有印...
    zyl06閱讀 11,375評論 19 14
  • 高級鉗工應知鑒定題庫(858題) ***單選題*** 1. 000003難易程度:較難知識范圍:相關4 01答案:...
    開源時代閱讀 5,776評論 1 9
  • 在以前的學校期奔,我們班成了一個組織——鐵三角。我危尿、王開禾呐萌、黃玉,三名成員形影不離脚线,吃飯時坐一起搁胆,下課也總是在一起玩,...
    北辰_9e51閱讀 420評論 5 5
  • 我的使命宣言:1邮绿、永遠保持積極主動的心態(tài)面對工作和生活渠旁;2、要謙虛船逮,不要驕傲顾腊;3、天天反释谖浮杂靶;4、通過刻意練習多維度...
    衡山閱讀 306評論 0 0