我一直在论坛上四处寻找,但我还没有找到任何足够具体的东西来解决我遇到的问题。我正在尝试在2D平台上创建一个碰撞检测函数,一开始我可以让它明确地命名每个顶点,然后玩家在碰撞时移动到它的位置,但这根本就没有效率,最终导致了大量的重新输入东西。它一开始会起作用,但随着时间的推移,它会变得比它的价值更麻烦。我正在尝试做一个碰撞检测功能,它将能够告诉我玩家在哪一边碰撞,并且能够将角色移动到适当的位置。我使用的是allegro 5和c++,到目前为止这是我的函数:
bool Collision(int x1,int y1,int h1,int w1,int x2,int y2,int h2,int w2){
if(x1 < x2 + w2 &&
x2 < x1 + w1 &&
y1 < y2 + h2 &&
y2 < y1 + h1)
{return 1;}
return 0;
}我如何才能使我的对象在碰撞时停止并不继续穿过该对象?但也要知道它落在了某个东西的顶部,或者撞到了它的侧面或底部,因为这些都是不同的反应。
发布于 2014-10-04 05:22:11
再次编辑如果希望对象在实际碰撞之前停止,而不共享相同的实际边缘像素,请尝试以下操作:
bool Collision(int x1,int y1,int h1,int w1,int x2,int y2,int h2,int w2){
if((x1 + w1) >= (x2 - 1) || // object 1 hitting left side of object 2
(x1 - 1) <= (x2 + w2) || // object 1 hitting right side of object 2
(y1 - 1) <= (y2 + h2) || // Object 1 hitting bottom of object 2 (assuming your y goes from top to bottom of screen)
(y1 + h1) >= (y2 - 1)) // Object 1 hitting top of object 2
return 1;
return 0;
}或
int Collision(int x1,int y1,int h1,int w1,int x2,int y2,int h2,int w2){
if((x1 + w1) >= (x2 - 1)) return 1; // object 1 hitting left side of object 2
if((x1 - 1) <= (x2 + w2)) return 2; // object 1 hitting right side of object 2
if((y1 - 1) <= (y2 + h2)) return 3; // Object 1 hitting bottom of object 2 (assuming your y goes from top to bottom of screen)
if((y1 + h1) >= (y2 - 1)) return 4; // Object 1 hitting top of object 2
return 0; // no collision
}这样一来,它们实际上就不应该共享同一个像素。
ORIGINAL我认为你想要做的更像是:
bool Collision(int x1,int y1,int h1,int w1,int x2,int y2,int h2,int w2){
if((x1 + w1) >= x2 || // object 1 hitting left side of object 2
x1 <= (x2 + w2) || // object 1 hitting right side of object 2
y1 <= (y2 + h2) || // Object 1 hitting bottom of object 2 (assuming your y goes from top to bottom of screen)
(y1 + h1) >= y2) // Object 1 hitting top of object 2
return 1;
return 0;
}这个答案假设你想知道他们两个完整的物体何时占据相同的坐标边(即小于/大于或等于与没有相等的对比)
但是,此答案不会返回哪条边是交互边。如果你想这样做,那么你可以沿着这些路线做更多的事情。
int Collision(int x1,int y1,int h1,int w1,int x2,int y2,int h2,int w2){
if((x1 + w1) >= x2) return 1; // object 1 hitting left side of object 2
if(x1 <= (x2 + w2)) return 2; // object 1 hitting right side of object 2
if(y1 <= (y2 + h2)) return 3; // Object 1 hitting bottom of object 2 (assuming your y goes from top to bottom of screen)
if((y1 + h1) >= y2) return 4; // Object 1 hitting top of object 2
return 0; // no collision
}现在,在外部,您只需解码1- 4的边缘检测案例。
https://stackoverflow.com/questions/26186856
复制相似问题