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

时间:2015-04-26 07:36:24

标签: c# xna monogame

我有两个矩形,一个玩家,一个地图。玩家需要无法浏览地图。玩家和地图都有一个带有位置和纹理宽度和高度的矩形,两者都有一个Vector位置。 Rectangle.Intersect()只输出一个布尔值,我无法弄清楚如何找出哪一侧与之相撞。我找到了这个函数here,它输出一个表示矩形重叠程度的Vector。

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玩家和地图值尝试相同时。

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

XNA中的jQueryUI Autocomplete类有4个可在此处使用的属性:

RectangleLeftTopRight

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

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

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

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

现在,即使它是3D格式,您也可能会发现Bottom有用。