我必须使用 Windows Forms 为学校制作一个游戏。我的游戏包括用户必须穿过迷宫。我试图阻止我的用户使用碰撞检测直接穿过墙壁,但由于用于表示墙壁的矩形形状不同而陷入困境。这是游戏的图像。 https://i.stack.imgur.com/adR4O.png这个问题可能类似于this one https://stackoverflow.com/questions/14132645/how-to-do-collision-detection-with-many-walls-maze,但是对于我的运动,我相信它是完全不同的,因为我没有布置网格系统或图形地图。
正如你所看到的,墙壁相当厚。每面墙都由一个 C# 表示Rectangle,
我的玩家图像(小黄鬼)也是如此。我知道如何使用 C# 确定玩家是否正在穿越这些墙壁IntersectsWith(Rectangle r)
方法,但我不太确定如何使用这些信息来处理碰撞并阻止玩家穿过墙壁。
这是我尝试过的:
这是我的实际运动代码。因为游戏是用WinForm构建的,所以移动是由键盘事件触发的,例如OnKeyPressed
and OnKeyUp
public void Move(Direction dir)
{
HandleCollision(); // Handle collision while player is trying to move.
if (dir == Direction.NORTH)
{
this.y -= moveSpeed;
}
if (dir == Direction.SOUTH)
{
this.y += moveSpeed;
}
if (dir == Direction.EAST)
{
this.x += moveSpeed;
}
if (dir == Direction.WEST)
{
this.x -= moveSpeed;
}
}
这是我的碰撞方法,HandleCollision()
:
private void HandleCollision()
{
// First, check to see if the player is hitting any of the boundaries of the game.
if (this.x <= 0)
{
this.x = 0;
}
if (this.x >= 748)
{
this.x = 748;
}
if (this.y <= 0)
{
this.y = 0;
}
if (this.y >= 405)
{
this.y = 405;
}
// Second, check for wall collision.
foreach (Rectangle wall in mazeWalls)
{
if (playerRectangle.IntersectsWith(wall))
{
if (player.X > wall.X) { player.X += wall.Width; }
else if (player.X < wall.X) { player.X -= wall.Width; }
else if (player.Y > wall.Y) { player.Y += wall.Height; }
else if (player.Y < wall.Y) { player.Y -= wall.Height; }
}
}
}
现在上面的代码kind of作品。然而,由于玩家的坐标添加了墙的宽度/高度,这会在地图上产生一些奇怪的碰撞传送,玩家最终会弹跳。那么,实现碰撞检测系统的最有效方法是什么,该系统可以替换if (playerRectangle.IntersectsWith(wall)) {
block?