gpt4 book ai didi

c++ - 二维碰撞 react

转载 作者:行者123 更新时间:2023-11-30 04:00:40 25 4
gpt4 key购买 nike

我一直在论坛上四处寻找,但我找不到足够具体的内容来解决我遇到的问题。我正在尝试在 2D 平台游戏中创建一个碰撞检测功能,起初我可以通过明确命名每个顶点以及玩家在碰撞时移动到的位置来使其工作,但这根本没有效率并最终结束有很多重新输入的东西。一开始它会起作用,但随着时间的推移,它会变得比它的值(value)更麻烦。我正在尝试制作一个碰撞检测功能,它能够告诉我玩家在哪一侧发生碰撞,并且能够将角色移动到正确的位置。我正在使用 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;
}

我怎样才能让我的物体在碰撞时停止而不继续穿过物体?但也知道它落在某物的顶部,或撞到它的侧面或底部,因为它们各自会有不同的 react 。

最佳答案

再次编辑如果您希望对象在实际碰撞之前停止而不共享相同的实际边缘像素,请尝试以下操作:

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
}

这样他们就永远不会共享相同的像素。

原创我认为你想去的地方更像是:

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;
}

此答案假定您希望知道它们何时完好无损地占据相同的坐标边缘(即小于/大于或等于与不等于)

但是,此答案不会返回 WHICH EDGE 是交互边。如果你想要那样,那么你可以按照这些思路做更多的事情。

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 的边缘检测情况。

关于c++ - 二维碰撞 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26186856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com