【发布时间】:2015-10-09 22:11:21
【问题描述】:
我在使用这个简单的碰撞算法时遇到了问题。我在做rpg game tutorial from codingmadeeasy,碰撞很像我在以前的平台风格游戏中做过的任何算法碰撞。以前的游戏我也遇到过这个问题,只是不记得修复了。我有一张地图,它有很多瓷砖,有些被标记为实心。他们的 Update 方法检查与玩家的碰撞。 如果瓷砖是实心的,它应该停止玩家并将他移动到一个有效的位置。
问题是当我向上或向下时,粘在瓷砖上,然后按向左或向右移动键。
例如:
我正在按下向下键,我在实心图块的顶部,然后按下向左。在那一刻,玩家被重新定位到瓷砖的右侧。
由于碰撞方法中的if顺序,如果我向左或向右并向上或向下按就不会发生这种情况。
public void Update(GameTime gameTime, ref Player player)
{
if (State != TileState.Solid) return;
Rectangle tileRect =
new Rectangle((int)Position.X, (int)Position.Y,
SourceRect.Width, SourceRect.Height);
Rectangle playerRect =
new Rectangle((int)player.Sprite.position.X, (int)player.Sprite.position.Y,
player.Sprite.SourceRect.Width, player.Sprite.SourceRect.Height);
HandleCollisionWithTile(player, playerRect, tileRect);
}
/// <summary>
/// Repositions the player at the current position after collision with tile
/// </summary>
/// <param name="player">the player intersecting with the tile</param>
/// <param name="playerRect">the rectangle of the player</param>
/// <param name="tileRect">the rectangle of the tile</param>
private static void HandleCollisionWithTile(Player player, Rectangle playerRect, Rectangle tileRect)
{
// Make sure there's even collosion
if (!playerRect.Intersects(tileRect)) return;
// Left
if (player.Velocity.X < 0)
player.Sprite.position.X = tileRect.Right;
// Right
else if (player.Velocity.X > 0)
player.Sprite.position.X = tileRect.Left - player.Sprite.SourceRect.Width;
// Up
else if (player.Velocity.Y < 0)
player.Sprite.position.Y = tileRect.Bottom;
// Down
else if (player.Velocity.Y > 0)
player.Sprite.position.Y = tileRect.Top - player.Sprite.SourceRect.Height;
// Reset velocity
player.Velocity = Vector2.Zero;
}
显然,如果我将前两个 if 和最后一个 if 互换,如果我从侧面过来按向上或向下,就会发生这种情况。
我到底错过了什么?
【问题讨论】:
-
看我对答案的评论。这个算法有底线问题
标签: c# collision-detection monogame