c++二维多边形碰撞检测

C++ 2D polygon Collision Detection

本文关键字:二维 多边形 碰撞检测 c++      更新时间:2023-10-16

我正在尝试使用图形包构建两个矩形来实现2D碰撞检测。不幸的是,我开始认为我不理解编写处理此问题的函数所需的逻辑。

下面是我绘制一个小精灵和几个其他矩形的代码。我的精灵随着键盘输入移动。

我使用了几本书,也尝试了像Nehe等网站,虽然他们是非常好的教程,但他们似乎只直接处理3D碰撞。

有人能告诉我一个有效的方法实现碰撞检测使用我的矩形上面?我知道你需要比较每个物体的坐标。我只是不确定如何跟踪对象的位置,检查碰撞和停止它的移动,如果它碰撞。

我正在自学,似乎已经停了好几天了。我完全没主意了,搜索了太多的谷歌页面。对不起,我太天真了。

我将感谢任何建设性的意见和示例代码。谢谢你。

    void drawSprite (RECT rect){
    glBegin(GL_QUADS);
        glColor3f(0.2f, 0.2f, 0.2f);
            glVertex3f(rect.x, rect.y, 0.0);
        glColor3f(1.0f, 1.0f, 1.0f);
            glVertex3f(rect.x, rect.y+rect.h, 0.0);
        glColor3f(0.2f, 0.2f, 0.2f);
            glVertex3f(rect.x+rect.w, rect.y+rect.h, 0.0);
        glColor3f(1.0f, 1.0f, 1.0f);
            glVertex3f(rect.x+rect.w, rect.y, 0.0);
    glEnd();
}
void drawPlatform (RECT rect){
    glBegin(GL_QUADS);
        glColor3f(0.2f,0.2f,0.0f);
            glVertex3f(rect.x, rect.y, 0.0);
        glColor3f(1.0f,1.0f,0.0f);
            glVertex3f(rect.x, rect.y+rect.h, 0.0);
        glColor3f(0.2f, 0.2f, 0.0f);
            glVertex3f(rect.x+rect.w, rect.y+rect.h, 0.0);
        glColor3f(1.0f, 1.0f, 0.0f);
            glVertex3f(rect.x+rect.w, rect.y, 0.0);
    glEnd();
}

您可以在绘图之前将此碰撞函数与AABB结构体(AABB代表对齐轴边界框)一起使用。

AABB.c

AABB* box_new(float x, float y, float w, float h, int solid)
{
    AABB* box = 0;
    box = (AABB*)malloc(sizeof(AABB*));
    box->x = (x) ? x : 0.0f;
    box->y = (y) ? y : 0.0f;
    box->width = (w) ? w : 1.0f;
    box->height = (h) ? h : 1.0f;
    return(box);
}
void box_free(AABB *box)
{
    if(box) { free(box); }
}
int collide(AABB *box, AABB *target)
{
    if
    (
        box->x > target->x + target->width &&
        box->x + box->width < target->x &&
        box->y > target->y + target->height &&
        box->y + box->height < target->y
    )
    {
        return(0);
    }
    return(1);
}

AABB.h

#include <stdio.h>
#include <stdlib.h>
typedef struct AABB AABB;
struct AABB
{
    float x;
    float y;
    float width;
    float height;
    int solid;
};
AABB* box_new(float x, float y, float w, float h, int solid);
void box_free(AABB *box);
int collide(AABB *box, AABB *target);

我希望它会有帮助!:)

仅仅检测碰撞是不够的,因为这会导致浮点精度问题。你能做的是检测重叠之间的矩形,如果这样的重叠发生碰撞已经发生,所以你可以碰撞出彼此的矩形。

同时,您需要将引擎分成两种状态:

  1. 矩形被输入
  2. 移动
  3. 重叠被检测到,如果发现矩形被移出彼此
  4. 显示场景

关于检测两个矩形是否重叠,请看这个问题:

确定两个矩形是否重叠?