矩形碰撞检测 SDL 2.0

rectangle colision detection SDL 2.0

本文关键字:SDL 碰撞检测      更新时间:2023-10-16

我在矩形碰撞方面遇到了问题,这是算法:

我检测 r1(renctangle 1) 是否高于 r2(矩形 2):

int BottomA = A.x+A.h;
int TopB = B.x;
if(TopB>BottomA)
{
Gravity();
}

但是相互重叠,我已经测试了在 60 种情况下限制一秒钟内或不受时间限制的 2 次重叠(10 或 15 像素,有时更少)。 重叠打破了横向碰撞的密码。

首先,碰撞检测与 SDL 无关。SDL 只显示内容。

您似乎正在使用轴对齐的框。轴对齐框的碰撞检测是最简单的条件。您只需在两个轴上检查它们(如果您在 3D 中工作,则在三个轴上检查它们)。如果任何轴不重叠,则两个框不重叠。

bool axis_check(int a_min, int a_max, int b_min, int b_max)
{
    if (a_max<b_min || b_max<a_min) return false;
    else return true;
}
bool box_collision(int a_x_min, int a_x_max, int a_y_min, int a_y_max,
                   int b_x_min, int b_x_max, int b_y_min, int b_y_max)
{
    if (axis_check(a_x_min, a_x_max, b_x_min, b_x_max)
     && axis_check(a_y_min, a_y_max, b_y_min, b_y_max))
        return true;
    else
        return false;
}

如果场景中有如此多的对象,则可以使用空间细分方法。有许多空间细分方法,例如递归划分为两个子空间,递归划分为八个子空间或网格。