多边形碰撞检测 -- 分离轴算法

多边形碰撞检测在游戏开发中是非常常用的算法,最直接的算法是检测两个多边形的每个点是否被包含,但是由于多边形的数量和多边形点的数量导致这种最直接的算法的效率非常之低。本文将介绍一个非常简单并且效率极高的算法——“分离轴算法”,并用C语言和Lua语言分别实现该算法,可以分别用于Cocos2d和Corona开发。

分离轴算法

图片
图片

上图就是分离轴算法的图示,首先需要知道分离轴算法只适用于“凸多边形”,但是由于“凹多边形”可以分成多个凸多边形组成,所以该算法可以用于所有多边形碰撞检测。不知道凹多边形是什么的看下图:


图片
图片

凹多边形就是含有顶点的内角度超过180°的多边形,反之就是凸多边形。

简单的说,分离轴算法就是指两个多边形能有一条直线将彼此分开,如图中黑线“Seperating line”,而与之垂直的绿线就是分离轴“Separating axis”。图中虚线表示的是多边形在分离轴上的投影(Projection)。详细的数学理论请查看wiki,我这里只讲该算法的实现方式。如果用伪代码来表示就是:

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所有的边,如果所有法线都不满足条件,则说明两多边形相交。

算法实现

首先我们需要定义几个数据类型和函数。
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);
}

有了数据类型然后就是算法的判断函数。
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为计算投影函数,先计算所有边长的投影,然后算出投影的最大和最小点即起始点;overlap函数判断两条线段是否重合。
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;
}

最后是算法实现函数,使用到上面的数据和函数。
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;
}

两个函数的使用方法很简单,只要定义好了多边形就行了。
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

完整的函数下载:LuaC

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,517评论 0 38
  • 前言 多边形偏移 (polygon offset) 算法可能我们印象不深,不过用过 autoCAD 的同学应该有印...
    zyl06阅读 10,466评论 17 14
  • 高级钳工应知鉴定题库(858题) ***单选题*** 1. 000003难易程度:较难知识范围:相关4 01答案:...
    开源时代阅读 5,270评论 1 9
  • 在以前的学校,我们班成了一个组织——铁三角。我、王开禾、黄玉,三名成员形影不离,吃饭时坐一起,下课也总是在一起玩,...
    北辰_9e51阅读 402评论 5 5
  • 我的使命宣言:1、永远保持积极主动的心态面对工作和生活;2、要谦虚,不要骄傲;3、天天反省;4、通过刻意练习多维度...
    衡山阅读 286评论 0 0