c++ - 二维碰撞检测分辨率

标签 c++ 2d collision-detection

我一直在使用我读过的一篇文章中的教程编写这个碰撞检测系统,但我终其一生都无法让它 100% 正确运行。 这是初学者的代码:

BoundingBox aBox;
aBox.Convert(a);
BoundingBox bBox;
bBox.Convert(b);

Vector2 aMin = aBox.GetTopLeft();
Vector2 aMax = aBox.GetBotRight();
Vector2 bMin = bBox.GetTopLeft();
Vector2 bMax = bBox.GetBotRight();

Vector2 minDistance;

float left = (bMin.x - aMax.x);
float right = (bMax.x - aMin.x);
float top = (bMin.y - aMax.y);
float bottom = (bMax.y - aMin.y);

// Check for intersection internally
if (left > 0 || right < 0) return;
if (top > 0 || bottom < 0) return;

// Find the minDistance
if (abs(left) < right)
    minDistance.x = left;
else
    minDistance.x = right;

if (abs(top) < bottom)
    minDistance.y = top;
else
    minDistance.y = bottom;

// Null axis with biggest value
if (abs(minDistance.x) < abs(minDistance.y))
    minDistance.y = 0;
else
    minDistance.x = 0;

现在的问题是,角色可以很好地行走和拥抱方 block 的顶部和底部,但是一旦他必须向上走两个方 block ,他就会卡在它们之间。巧合的是,走下去效果很好。只是想知道是否有人能解决这个问题,将不胜感激!

这里有一个 gif 可以更好地显示问题:

enter image description here

最佳答案

好吧,这可能更像是一种解决方法而不是实际修复,但是在处理您的输入时,您可以检查您要移动的方向是否有空间。

如果向左上方向移动,可以检查左边是否有空间,如果没有,则只应用移动的垂直分量。同样适用于四个方向。

大多数此类错误来自舍入数字的工作方式,如果您想要一致且良好的行为,请努力避免这些舍入数字情况,就像我刚刚给您的示例一样。

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

相关文章:

c++ - Qt:Qt5 Windows 中 BitBlt 的替代品

c++ - 如何在图像上绘制模糊矩形?

c# - 如何实现场景中 "kill"事件的感知

java - Libgdx 碰撞问题

algorithm - 查找两个移动、旋转边界框相交的时间和位置

c++ - 在数组中查找最小值

c++ - 指向字符串和字符的指针捕获 22

c++ - 在ubuntu上安装node js pulsar客户端

c++ - 使用 tmx-parser 和 SDL 的 2d tile 渲染

collision-detection - 涉及快速旋转物体的碰撞检测