【发布时间】: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 播放器和地图值进行相同操作时。
问题:如何在单人游戏中使用矩形来进行碰撞检测,让您知道哪一侧被碰撞,使用此功能或其他方式。
感谢您的帮助!
【问题讨论】: