這是一個跟進問題到question that I posted last night。我必須在Windows Form中爲學校編寫一款遊戲,並且我正在創建一個迷宮遊戲,玩家必須在他們被殺之前在迷宮中導航。作爲迷宮遊戲,必須使用一些碰撞檢測來確保玩家不會簡單地穿過牆壁(這將是一個非常無聊的遊戲)。我已經實現了一個基於昨晚我問過的問題來防止這個問題的功能,但是我得到了一些奇怪的結果。二維窗體中奇怪的粘性碰撞檢測窗體遊戲
當玩家觸摸牆壁時,遊戲停止,玩家最終陷入困境。玩家不能移動,除非他們按下組合鍵移動穿過牆壁(我的遊戲使用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
確保您的代碼邏輯牢固。代碼可能有可能在同一時間檢查兩個按鍵事件,然後違反邏輯。嘗試確保只有按鍵事件檢查僅在獨佔模式下工作,例如使用線程等待/阻塞進行最後一個事件(排隊方法)。 – Kelmen
@Kelmen你想我發佈我的鍵盤輸入代碼嗎?因爲遊戲是在WinForm中構建的,所以輸入是由鍵盤事件處理的,說實話我並不知道很多。如果你願意,我可以發佈。 – MrSir
對不起,我對代碼審查不感興趣。我正在給你一個方向如何改進/調試你的代碼。 如果你不知道如何處理這個問題,就像使用Debug.WriteLine(「x is」+ x.ToString())。並試圖在dev模式下重現此問題,當它發生時,查看VS輸出窗口,檢查消息,查看是否將x值更改爲某個意外值,並追溯代碼,添加更多內容以查明原因。 – Kelmen