【问题标题】:2D Monogame: Rectangle collision detection, side specific2D Monogame:矩形碰撞检测,侧面特定
【发布时间】:2015-04-28 16:00:27
【问题描述】:

我有两个矩形,一个玩家,一张地图。玩家需要不能穿过地图。玩家和地图都有一个带有位置和纹理宽度和高度的矩形,也都有一个矢量位置。 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 播放器和地图值进行相同操作时。

问题:如何在单人游戏中使用矩形来进行碰撞检测,让您知道哪一侧被碰撞,使用此功能或其他方式。

感谢您的帮助!

【问题讨论】:

    标签: c# xna monogame


    【解决方案1】:

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

    LeftTopRightBottom

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

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

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

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

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

    【讨论】:

    • 哦,哇,不知道矩形有那个。也没想过尝试使用中点。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多