我是c++的新手,我一直在一个小游戏程序中练习碰撞,这个小游戏什么也不做,我就是不能正确地进行碰撞
所以我使用加载到变量中的图像
background = oslLoadImageFile("background.png", OSL_IN_RAM, OSL_PF_5551);
sprite = oslLoadImageFile("sprite.png", OSL_IN_RAM, OSL_PF_5551);
bush = oslLoadImageFile("bush.png", OSL_IN_RAM, OSL_PF_5551);虽然有一些变量存储为
sprite->x = 3;
if ( (sprite->x + spritewidth > bush->x) && (sprite->x < bush->x + bushwidth) && (sprite->y + spriteheight > bush->y) && (sprite->y < bush->y + bushheight) )
{
bushcol = 1;
}
else
{
bushcol = 0;
}所以当我按下一个按钮
if (osl_keys->held.down)
{
if (bushcol == 1)
{
sprite->y = bush->y + 38;
}
else
{
sprite->y += 3;
}
}
if (osl_keys->held.up)
{
if (bushcol == 1)
{
sprite->y = bush->y - 23;
}
else
{
sprite->y -= 3;
}
}
if (osl_keys->held.right)
{
if (bushcol == 1)
{
sprite->x = bush->x - 28;
}
else
{
sprite->x += 3;
}
}
if (osl_keys->held.left)
{
if (bushcol == 1)
{
sprite->x = bush->x + 28;
}
else
{
sprite->x -= 3;
}
}我在想像这样的事情
sprite->y = bushheight - 24;但它不起作用
有什么建议吗?
发布于 2009-05-14 19:42:26
我想你已经有了基本的想法。检查一下你的工作。这是一个简单的版本,它编译:
#import <stdlib.h>
typedef struct {
// I'm going to say x, y, is in the center
int x;
int y;
int width;
int height;
} Rect;
Rect newRect(int x, int y, int w, int h) {
Rect r = {x, y, w, h};
return r;
}
int rectsCollide(Rect *r1, Rect *r2) {
if (r1->x + r1->width/2 < r2->x - r2->width/2) return 0;
if (r1->x - r1->width/2 > r2->x + r2->width/2) return 0;
if (r1->y + r1->height/2 < r2->y - r2->height/2) return 0;
if (r1->y - r1->height/2 > r2->y + r2->height/2) return 0;
return 1;
}
int main() {
Rect r1 = newRect(100,200,40,40);
Rect r2 = newRect(110,210,40,40);
Rect r3 = newRect(150,250,40,40);
if (rectsCollide(&r1, &r2))
printf("r1 collides with r2\n");
else
printf("r1 doesnt collide with r2\n");
if (rectsCollide(&r1, &r3))
printf("r1 collides with r3\n");
else
printf("r1 doesnt collide with r3\n");
}发布于 2009-05-14 19:12:59
我建议仅为检测边界框冲突的目的创建一个函数。它可能看起来像
IsColiding(oslImage item1, oslImage item2)
{
/* Perform check */
} 检查图像1和图像2之间是否存在冲突。至于您尝试使用的算法,请查看此维基百科,例如AABB bounding box
尤其是这一部分:
在AABB的情况下,这个测试变成了一组关于单元轴的简单的重叠测试。对于由M,N定义的AABB和由O,P定义的AABB,如果(Mx>Px)或(Ox>Nx)或(My>Py)或(Oy>Ny)或(Mz>Pz)或(Oz>Nz)不相交,则它们不相交。
发布于 2009-05-14 19:31:43
首先我想你的意思是
sprite->y = bush->**y** - 3;
其次,我不知道你使用的是什么平台,但经常y坐标是颠倒的。即y=0对应于屏幕的顶部。在这种情况下,您的比较可能不起作用。
第三,添加旋转和非矩形对象时,碰撞检查可能会很快变得复杂。您应该考虑使用CGAL或其他一些计算几何算法库,它们可以处理多边形相交。
https://stackoverflow.com/questions/865000
复制相似问题