2D碰撞检测分辨率

时间:2014-03-13 08:47:03

标签: 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;

现在的问题是这个角色很好地走路并拥抱一个街区的顶部和一个街区的底部,但是一旦他必须向上走两个街区,他就会卡在他们之间。巧合的是,走路时效果非常好。只是想知道是否有人有这个问题的解决方案,我将不胜感激!

这是一个更好地展示问题的gif:

enter image description here

1 个答案:

答案 0 :(得分:0)

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

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

大多数这类错误都来自于编辑数字的工作方式,如果你想要一致且好的行为,那就是如何避免这些舍入数字情况,就像我刚刚给你的例子一样。