跳至內容

使用 XNA 建立簡單 3D 遊戲/新增控制

來自華夏公益教科書,開放世界開放書籍

接收鍵盤輸入

[編輯 | 編輯原始碼]

為了處理遊戲的輸入,我們將從鍵盤接收輸入,然後用於移動魚在景觀中移動,並退出遊戲。

首先在您的 Game1 檔案中建立一個名為“HandleInput”的新方法,並建立一個新的鍵狀態變數。當呼叫此方法時,鍵盤的當前狀態將儲存為鍵狀態變數的一部分,然後可以由遊戲邏輯訪問。

//Handles input
private void HandleInput(GameTime gameTime)
{
    KeyboardState currentKeyboardState = Keyboard.GetState();
}

接下來新增以下條件語句。

// Check for exit.
if (currentKeyboardState.IsKeyDown(Keys.Escape))
{
    Exit();
}

這提供了最簡單的解釋這種過程工作原理的方法,您可以將它作為任何條件語句的一部分構建,以監控任何鍵的位置。在您的更新程式碼中放置對該方法的呼叫,使用“gameTime”變數作為引數(我們將在後面使用)。有了這段程式碼,您應該能夠透過按 Escape 鍵隨時退出程式碼。

接下來,我們將放置一個類似的條件語句來使用箭頭鍵。在您的“HandleInput”方法中新增以下幾行。

//Move the fish with the arrow keys
float speed = 0.02f; //Dictates the speed
if (currentKeyboardState.IsKeyDown(Keys.Left))
{
    FishMen.Translation.Y -= speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
}
if (currentKeyboardState.IsKeyDown(Keys.Right))
{
    FishMen.Translation.Y += speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
}
if (currentKeyboardState.IsKeyDown(Keys.Up))
{
    FishMen.Translation.X += speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
}
if (currentKeyboardState.IsKeyDown(Keys.Down))
{
    FishMen.Translation.X -= speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
}

為了使效果更明顯,請更改 Update 方法中的以下幾行。

cameraPosition = cameraTarget = FishMen.Translation;
cameraPosition.Z += 20.0f;

cameraPosition = cameraTarget = FishMen.Translation / 2;
cameraPosition.Z -= 20.0f;

並執行程式碼。這應該會生成您魚的肩上視角,因為它在周圍移動。使用“ElapsedGameTime”變數的邏輯,它監控更新方法呼叫之間的時間差,補償幀之間處理時間的任何變化。如果不是這樣,您的計算機越快,控制就越不穩定,越快。實際上,它應該在計算機之間保持一致。執行程式碼,您應該看到它隨著箭頭鍵的按下而移動。

最後,為了確定魚的邊界,建立一個名為“boundarys”的新“Vector2”變數,它將決定魚在二維空間中的最大位置。更改您的箭頭鍵處理程式碼如下所示。

//Move the fish with the arrow keys
float speed = 0.02f; //Dictates the speed
Vector2 boundarys = new Vector2(14f);

if (currentKeyboardState.IsKeyDown(Keys.Left) && FishMen.Translation.Y > -boundarys.Y)
{
    FishMen.Translation.Y -= speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
}
if (currentKeyboardState.IsKeyDown(Keys.Right) && FishMen.Translation.Y < boundarys.Y)
{
    FishMen.Translation.Y += speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
}
if (currentKeyboardState.IsKeyDown(Keys.Up) && FishMen.Translation.X < boundarys.X)
{
    FishMen.Translation.X += speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
}
if (currentKeyboardState.IsKeyDown(Keys.Down) && FishMen.Translation.X > -boundarys.X)
{
    FishMen.Translation.X -= speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
}

這應該會生成一個遊戲,其中魚只移動到特定位置並停止。您可以隨意調整移動,透過監控“boundary”和“speed”變數來調整您的喜好。

華夏公益教科書