我必須爲Windows Forms製作一款適合學校的遊戲。我的遊戲包含一個用戶不得不通過迷宮。我試圖阻止我的用戶使用碰撞檢測直接穿過牆壁,但是由於用於表示牆的矩形的形狀不同而陷入困境。 Here's an image of the game.這個問題可能類似於this one,但是隨着我的運動,我相信它是完全不同的,因爲我沒有佈置網格系統或圖形地圖。壁厚較厚的2D迷宮中的碰撞檢測
正如你所看到的,牆壁相當厚。每個牆都以C#Rectangle,
代表,就像我的播放器圖像(小黃色幽靈)一樣。我知道如何確定玩家是否使用C#的IntersectsWith(Rectangle r)
方法穿過這些牆壁,但我不確定如何使用這些信息來處理碰撞並阻止玩家穿過牆壁。
這是我試過的:
這是我的實際運動代碼。因爲遊戲是建立在winform,該運動是由鍵盤事件觸發如OnKeyPressed
和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; }
}
}
}
下面這段代碼種作品。然而,由於玩家的座標已經增加了牆的寬度/高度,這會在地圖上發生一些奇怪的碰撞傳送,玩家最終會彈跳。那麼,實現碰撞檢測系統的最有效方法是什麼?它可以替代if (playerRectangle.IntersectsWith(wall)) {
塊中的所有代碼?