首页 > 解决方案 > SFML 2.5.1 的问题:碰撞检测不起作用

问题描述

你能帮我解决我在这里做错了什么吗?

我在 YT 上遵循了本教程:https ://www.youtube.com/watch?v=l2iCYCLi6MU&t=605s 进行碰撞检测,但我的企鹅似乎穿过了我的物体。我很沮丧。

我使用的 sfml 版本是 2.5.1。我使用 Visual Studio 2017。

我保证,在我在这里链接的文件中没有病毒。 https://drive.google.com/drive/folders/16vl1Kkv-O5IRb8Svu71qLPXRkn3eINf1?usp=sharing

(更新 - 我通过替换解决了这个问题

float intersectX = abs(deltax) - (otherHalfSize.x + thisHalfSize.x); float intersectY = abs(deltay) - (otherHalfSize.y + thisHalfSize.y);

所以我用加号改变了减号,但现在推动顺序只能从底部和右侧起作用,但是当我尝试向左推动时,对象立即站在角色的头上。我失败了什么?

有些人对病毒持怀疑态度,所以我将粘贴代码:

这是标题碰撞器的代码

Whatch 视频并告诉我我可能做错了什么。

sf::Vector2f otherPosition = other.getPosition();
sf::Vector2f otherHalfSize = other.gethalfsize();
sf::Vector2f thisPosition = getPosition();
sf::Vector2f thisHalfSize = gethalfsize();

float deltax = otherPosition.x - thisPosition.x;
float deltay = otherPosition.y - thisPosition.y;

float intersectX = abs(deltax) - (otherHalfSize.x + thisHalfSize.x);
float intersectY = abs(deltay) - (otherHalfSize.y + thisHalfSize.y);

if (intersectX < 0.0f and intersectY < 0.0f)
{
    push = std::min(std::max(push, 0.0f), 1.0f);
    if (intersectX > intersectY) // ricordo che adesso stiamo utilizzando numeri negativi
    {
        if (deltax > 0.0f)
        {
            Move(intersectX * (1.0f - push), 0.0f);
            other.Move(-intersectX * push, 0.0f);
        }
        else
        {
            Move(intersectX * (1.0f - push), 0.0f);
            other.Move(intersectX * push, 0.0f);
        }

    }
    else
    {
        if (deltay > 0.0f)
        {
            Move(0.0f, intersectY * (1.0f - push));
            other.Move(0.0f, -intersectY * push);
        }
        else
        {
            Move(0.0f, intersectY * (1.0f - push));
            other.Move(0.0f, intersectY * push);
        }
    }
    return true;
}
return false;

标签: c++collision-detectionsfmlcollision

解决方案


我发现了问题:

我需要改变这个:

Move(intersectX * (1.0f - push), 0.0f);

对此:

Move(-intersectX * (1.0f - push), 0.0f);

Y轴上也一样。我整晚都在寻找这个愚蠢的错误。


推荐阅读