带轴向矩形判断相交 OBB 判断相交

122 阅读1分钟

OBB 判断相交

分离轴定理 两个凸多边形不相交的充要条件是存在一条直线,使得两个多边形在这条直线的投影不相交

该直线为平行与两个多边形的某一条边或者是两个多边形的某一条边的法线

2D OBB

image.png

求解找到一条直线把俩个OBB分离开来 <==> 找这条直线的垂线,并且两个OBB在这条直线上的投影没有交集。

image.png

OBB 表示

struct OBB{
    Vector3 axis[2]; // 两个轴向
    Vector3 vertex[4]; // 四个顶点
}

求解过程如下:

只要求取OBB四个顶点在某一条垂线上投影的最大最小值,再根据AABB的方法可判断是否存在垂线对应的分离轴。

image.png

OBB obb1, obb2;

Vector3 axis[4] = {obb1.axis[0], obb1.axis[1], obb2.axis[0], obb2.axis[1]}; // 两个OBB的轴向

for(int i = 0; i < 4; i++){
    Vector3 axis = axis[i];
    float min1 = dot(axis, obb1.vertex[0]);
    float max1 = min1; // OBB1 在axis上的投影
    for(int j = 1; j < 4; j++){
        float proj = dot(axis, obb1.vertex[j]); // 点乘求投影长度,axis可归一化,不归一化也行
        if(proj < min1) min1 = proj;
        if(proj > max1) max1 = proj;
    }

    float min2 = dot(axis, obb2.vertex[0]);
    float max2 = min2; // OBB2 在axis上的投影
    for(int j = 1; j < 4; j++){
        float proj = dot(axis, obb2.vertex[j]); 
        if(proj < min2) min2 = proj;
        if(proj > max2) max2 = proj;
    }

    if(max1 < min2 || max2 < min1){ // 类似AABB的判断方式
        return false;
    }
}