c++二维多边形碰撞检测
C++ 2D polygon Collision Detection
我正在尝试使用图形包构建两个矩形来实现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);
我希望它会有帮助!:)
仅仅检测碰撞是不够的,因为这会导致浮点精度问题。你能做的是检测重叠之间的矩形,如果这样的重叠发生碰撞已经发生,所以你可以碰撞出彼此的矩形。
同时,您需要将引擎分成两种状态:
- 矩形被输入 移动
- 重叠被检测到,如果发现矩形被移出彼此
- 显示场景
关于检测两个矩形是否重叠,请看这个问题:
确定两个矩形是否重叠?
相关文章:
- 将二维矢量传递给类
- 将值从二维数组输出到文本文件
- 我在二维向量中是否正确分配了内存
- 带结构的二维矢量:如何存储元素
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在C++中获取二维数组中最少的一列数?
- 如何使用用户输入变量制作二维数组?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- C++ 中动态二维数组的访问冲突
- 在二维向量或数组中可以存储的最大元素数是多少?
- 如何将整数字符串转换为整数的二维向量?
- 向二维多边形添加点
- 用于二维数组中循环的特殊多边形
- c++二维多边形碰撞检测
- 多边形点从三维到二维的正交投影,用于UV贴图