【发布时间】:2013-12-16 13:34:17
【问题描述】:
这是question that I posted last night 的后续问题。我必须为学校编写一个 Windows 窗体的游戏,我正在创建一个迷宫游戏,其中玩家必须在被杀死之前穿过迷宫。作为迷宫游戏,必须使用一些碰撞检测来确保玩家不会简单地穿过墙壁(这将是一个非常无聊的游戏)。根据我昨晚提出的问题,我已经实现了一项防止这种情况发生的功能,但我得到了一些奇怪的结果。
当玩家碰到墙时,游戏会阻止他们,玩家最终会被卡住。玩家不能移动,除非他们按下组合键穿过墙(我的游戏使用 WASD,所以如果我碰到墙,我可以按 W + A 并穿过墙到另一边,我的玩家会被卡住) .
这是我的碰撞代码:
// This goes in the main class
foreach (Rectangle wall in mazeWalls)
{
if (playerRectangle.IntersectsWith(wall))
{
player.Stop();
}
}
这是玩家的移动代码:
public void Move(Direction dir)
{
// First, check & save the current position.
this.lastX = this.x;
this.lastY = this.y;
if (dir == Direction.NORTH)
{
if (!CheckCollision())
{
this.y -= moveSpeed;
}
else
{
this.y += 1;
}
}
else if (dir == Direction.SOUTH)
{
if (!CheckCollision())
{
this.y += moveSpeed;
}
else
{
this.y -= 1;
}
}
else if (dir == Direction.EAST)
{
if (!CheckCollision())
{
this.x += moveSpeed;
}
else
{
this.x -= 1;
}
}
else if (dir == Direction.WEST)
{
if (!CheckCollision())
{
this.x -= moveSpeed;
}
else
{
this.x += 1;
}
}
}
我的CheckCollision() 方法:
private bool CheckCollision()
{
// First, check to see if the player is hitting any of the boundaries of the game.
if (this.x <= 0)
{
isColliding = true;
}
else if (this.x >= 748)
{
isColliding = true;
}
else if (this.y <= 0)
{
isColliding = true;
}
else if (this.y >= 405)
{
isColliding = true;
}
else if (isColliding)
{
isColliding = false;
}
// Second, check for wall collision.
return isColliding;
}
Stop() 方法:
public void Stop()
{
this.x = lastX;
this.y = lastY;
}
Here 是我上传的 gif,以便您可以看到玩家在迷宫墙中的行为。注意他是如何滑过墙壁并反复卡住的。
我的问题是我如何让这个播放器停止粘着并真正能够随着墙壁滑动和移动?我尝试了多种碰撞模式,并使用了昨晚的(非常有帮助的)答案,但他不会停止粘在墙上!如果您需要任何其他详细信息/信息,请告诉我。
编辑:Dan-o 要求的输入代码:http://pastebin.com/bFpPrq7g
【问题讨论】:
-
确保您的代码逻辑可靠。代码可能会在大约同一时间执行检查 2 个按键事件,然后破坏您的逻辑。尝试确保只有按键事件检查仅在独占模式下工作,例如对最后一个事件使用线程等待/阻塞(排队方法)。
-
@Kelmen 你想让我发布我的键盘输入代码吗?因为游戏是在 WinForm 中构建的,所以输入是由键盘事件处理的,老实说,我对此并不了解。如果你愿意,我可以发布。
-
抱歉,我对代码审查不感兴趣。我给你一个方向如何改进/调试你的代码。如果你不知道如何解决这个问题,比如使用 Debug.WriteLine("x is " + x.ToString())。并尝试在开发模式下重现此问题,当它发生时,查看您的 VS 输出窗口,检查消息,查看 x 值是否更改为某个意外值,并追溯您的代码,添加更多内容以查明原因。
-
@Kelmen 谢谢。这不是真正的代码审查。我只是想看看发布这种代码是否有助于解决问题。
-
@MrSir:是的,请贴出键盘输入代码。
标签: c# winforms collision-detection collision