gpt4 book ai didi

c# - 2D Monogame : Rectangle collision detection, 边特定

转载 作者:行者123 更新时间:2023-12-04 18:04:15 27 4
gpt4 key购买 nike

我有两个矩形,一个玩家,一张 map 。玩家需要无法穿过 map 。播放器和 map 都有一个带有位置和纹理宽度和高度的矩形,它们也都有一个矢量位置。 Rectangle.Intersect() 仅输出一个 bool 值,我无法弄清楚如何找出与哪一侧发生碰撞。我找到了这个功能 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 玩家和 map 值进行相同操作时。

问题:如何使用此函数或其他方式在带有矩形的单人游戏中完成碰撞检测,让您知道与哪一侧发生碰撞。

感谢您的帮助!

最佳答案

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

Left , Top , RightBottom .

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

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

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

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

现在,即使它是 3D 的,您也可能会发现 this post有帮助。

关于c# - 2D Monogame : Rectangle collision detection, 边特定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29874994/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com