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

3
我有两个矩形,一个玩家,一个地图。玩家不能穿过地图。玩家和地图都有一个位置和纹理宽度和高度的矩形,也都有一个向量位置。Rectangle.Intersect()只输出一个布尔值,我无法确定碰撞发生在哪一侧。我在这里找到了这个函数(链接),它输出一个向量表示矩形重叠的程度。
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中使用矩形进行碰撞检测,并让您知道与哪一侧发生了碰撞。

感谢任何帮助!

1个回答

1

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

LeftTopRightBottom

您可以使用这些属性确定碰撞发生的位置。

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

基本上,您可以比较两个矩形的X和Y坐标。除了一些奇怪的情况(如一个矩形完全被另一个矩形包含在内,或一个矩形是另一个矩形的超集),这些信息足以告诉您它们碰撞的方向。

更好的方法是通过查找两个形状的中心点,这也可能是判断两个对象相对位置的更容易的方法。

即使是在三维空间中,您也可能会发现this post有所帮助。


哦,哇,我不知道矩形有那个功能。我也没想到可以使用中点。感谢您的帮助。 - T. Croll

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接