【发布时间】:2020-08-04 21:59:05
【问题描述】:
我正在尝试使用 MonoGame(它使用 XNA 的框架)为我的大学项目创建一个 2D 游戏,并且在两个重叠的矩形和一个玩家“Hitbox”矩形之间发生碰撞时遇到了很多麻烦。 如果玩家正在沿一个墙矩形对角线移动,而遇到另一个不碍事的垂直墙矩形,则玩家将被停止(这不是预期的结果)。
当玩家走进墙时,将调用 Player 类的 CollisionHandler 方法,并通过参数提供碰撞的 Rectangle 以及枚举 Side(本质上是 Wall 检查碰撞的方式)。该方法有一些条件,然后改变玩家的位置。这是它的代码:
public void CollisionHandler(Rectangle Wall, Side TestSide) // Assuming Hitbox and Wall are Intersecting
{
if ((TestSide == Side.Up && Direction.Y > 0) // If the Wall is testing for collision Upwards and the Player is moving Downwards through it
|| (TestSide == Side.Down && Direction.Y < 0)) // or if the Wall is testing for collision Downwards and vice versa
{
Position.Y -= Direction.Y * MovementSpeed; // Y movement is reversed
}
if ((TestSide == Side.Left && Direction.X > 0) // If the Wall is testing for collision to it's Left and the Player is moving to the Right through it
|| (TestSide == Side.Right && Direction.X < 0)) // or if the Wall is testing for collision to it's Right and vice versa
{
Position.X -= Direction.X * MovementSpeed; // X movement is reversed
}
}
(方向是玩家的新位置减去他们之前的位置的归一化向量2)
问题是当玩家移动到两个重叠墙的角落时。 例如,这是我在地图上的两堵墙:
Walls.Add(new Rectangle(360, 240, 1, 120)); // Side = Side.Left
Walls.Add(new Rectangle(360, 240, 120, 1)); // Side = Side.Up
当玩家沿对角线向下和向右移动时(方向大致为 (0.707, 0.707)),“左”向的墙会与玩家的 Hitbox 相交,尽管玩家的 Hitbox 位于墙的后面和上方,从而减少播放器停止。
我已经尝试过很多次来解决这个问题,通常是通过改变墙的制作方式,而这实际上是墙呈现方式的最新迭代。在此之前,它们只是游戏中每个 Tile 上的大矩形,“CanEnter”属性为 false。
我已经断断续续地思考了几个星期,试图弄清楚如何才能防止这种情况发生,但实际上没有任何效果,现在我的项目由于这个问题而完全停滞不前。 我真的很感激一些关于如何解决这个问题的帮助或指示。
【问题讨论】:
-
你的
Rectangle HitBox是在Rectangle Wall里面还是外面? -
@AzuxirenLeadGuy 问题发生时,矩形 HitBox 位于矩形墙内; CollisionHandler 检测到这一点并编辑 Player 的位置。