2D Monogame:矩形碰撞检测,边特定

2D Monogame: Rectangle collision detection, side specific

我有两个矩形,一个玩家,一张地图。玩家需要无法穿过地图。播放器和地图都有一个带有位置和纹理宽度和高度的矩形,它们也都有一个矢量位置。 Rectangle.Intersect() 只输出一个布尔值,我无法弄清楚如何找出碰撞的一侧。我发现这个函数 here 输出一个表示矩形重叠多少的向量。

public static Vector2 GetIntersectionDepth(this Rectangle rectA,                 Rectangle rectB)
    {
        // Calculate half sizes.
        float halfWidthA = rectA.Width / 2.0f;
        float halfHeightA = rectA.Height / 2.0f;
        float halfWidthB = rectB.Width / 2.0f;
        float halfHeightB = rectB.Height / 2.0f;

        // Calculate centers.
        Vector2 centerA = new Vector2(rectA.Left + halfWidthA, rectA.Top + halfHeightA);
        Vector2 centerB = new Vector2(rectB.Left + halfWidthB, rectB.Top + halfHeightB);

        // Calculate current and minimum-non-intersecting distances between centers.
        float distanceX = centerA.X - centerB.X;
        float distanceY = centerA.Y - centerB.Y;
        float minDistanceX = halfWidthA + halfWidthB;
        float minDistanceY = halfHeightA + halfHeightB;

        // If we are not intersecting at all, return (0, 0).
        if (Math.Abs(distanceX) >= minDistanceX || Math.Abs(distanceY) >= minDistanceY)
            return Vector2.Zero;

        // Calculate and return intersection depths.
        float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
        float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
        return new Vector2(depthX, depthY);
    }

这个函数会根据边给出负数,但是我不知道如何有效地使用它们。我试过了:

Vector2 overlap =   RectangleExtensions.GetIntersectionDepth(map.Dungeon[x,y].BoundingBox, player.BoundingBox);
if (overlap.X > 0) //This should be collision on the left
{
    //Move the player back
}

然而,这会导致一些奇怪的错误,尤其是在尝试对 Y 玩家和地图值进行相同操作时。

问题:如何在 monogame 中使用矩形进行碰撞检测,让您知道哪一侧发生碰撞,使用此函数或其他方式。

感谢您的帮助!

XNA 中的 Rectangle class 有 4 个属性可以在这里使用:

Left, Top, Right and Bottom.

您可以使用这些来确定碰撞发生在哪一侧。

例如,考虑 Player.Rectangle.Left > Map.Rectangle.Left。如果这是真的,那么碰撞可能发生在右侧(假设玩家的左侧在 X 轴上比地图的大,这意味着玩家在地图最左边的点的右边)地图)。

基本上你可以比较两个矩形的 X 和 Y 坐标。除了奇怪的情况(比如一个矩形完全淹没在另一个矩形中,或者一个矩形是另一个矩形的超集)这些应该足以告诉你它们碰撞的一侧。

检查这一点的更好方法是使用两个形状的中点,这也可能是判断两个对象相对位置的更简单方法。

现在,即使是 3D 格式,您也会发现 this post 有帮助。