1

更新

再次更改了碰撞代码并为 AABB 制作了一个组件,现在看来问题仅在于水平碰撞,它并没有将物体推到它认为的足够但与 Y 轴相同的代码,所以它不应该是一个问题.

(它确实检测到水平碰撞,分辨率是问题)

图片

void Hermes_Player::Collision(GameObject * other)
{
    if (other->GetTag() == "wall") {
        AABB* myAABB = dynamic_cast<AABB*>(this->GetComponent("aabb"));
        AABB* otherAABB = dynamic_cast<AABB*>(other->GetComponent("aabb"));
        if (abs(myAABB->lastCenter.x - otherAABB->lastCenter.x) < myAABB->halfCenter.x + otherAABB->halfCenter.x) {
            std::cout << "y" << std::endl;
            if (myAABB->center.y < otherAABB->center.y) {
                int distance = (myAABB->halfCenter.y + otherAABB->halfCenter.y) - (otherAABB->center.y - myAABB->center.y);
                this->Position.y -= distance;
                myAABB->center.y = (myAABB->center.y - distance);
            }
            if (myAABB->center.y > otherAABB->center.y) {
                int distance = (myAABB->halfCenter.y + otherAABB->halfCenter.y) - (myAABB->center.y - otherAABB->center.y);
                this->Position.y += distance;
                myAABB->center.y = (myAABB->center.y + distance);
            }
        }
        else
        {
            std::cout << "x" << std::endl;

            int dist = myAABB->halfCenter.x + otherAABB->halfCenter.x;
            int dif = (this->Size.x + other->Size.x) /2- abs(dist);
            if (myAABB->center.x < otherAABB->center.x) {
                int distance = (myAABB->halfCenter.x + otherAABB->halfCenter.x) - (otherAABB->center.x - myAABB->center.x);
                this->Position.x -= distance;
                myAABB->center.x = (myAABB->center.x - distance);
            }
            if (myAABB->center.x > otherAABB->center.x) {
                int distance = (myAABB->halfCenter.x + otherAABB->halfCenter.x) - (myAABB->center.x - otherAABB->center.x);
                this->Position.x += distance;
                myAABB->center.x = (myAABB->center.x + distance);
            }
            std::cout << this->Position.x << std::endl;
        }
    }
}
4

2 回答 2

1

我没有调试/阅读整个代码,但这看起来是一个经典问题。一旦检测到碰撞,您就可以通过单一方向和穿透来解决它。

发生的情况是,在移动和碰撞之后,解决一个轴可能会使另一个轴仍然存在碰撞。从那里开始,一切都崩溃了。

或者你可能与两个物体发生碰撞,解决第二个物体会让你回到你已经调整过的物体。

至少,在调整回位置之后,您需要检查它是否全部清晰,对于所有对象。

于 2018-09-27T01:40:16.917 回答
1

这可能不是您要寻找的,但尝试同时解析 X 和 Y 轴可能会相当复杂。

一种解决方案可能是独立步进每个轴并分别解决它们的碰撞。

您必须执行两次碰撞检测,但它使分辨率更简单,IE 无需检查碰撞分辨率是否导致更多碰撞,您只需停止沿第一个碰撞对象边缘的移动即可。

这是一篇帮助我开发自己的 2D 平台游戏的文章,它推荐了这种做法:

http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/

于 2018-09-27T03:22:28.787 回答