延續第一章的 Hello World,本章實作 Sprite 的鍵盤/滑鼠雙模式控制,並引入 A* 演算法處理滑鼠點擊的路徑尋找。
Keyboard.GetState() 取得按鍵狀態。Mouse.GetState() 取得座標與按鍵。GamePad.GetState(PlayerIndex.One) 處理手柄(預設範本用 Back 鍵離開)。protected override void Update(GameTime gameTime)
{
KeyboardState state = Keyboard.GetState();
if (state.IsKeyDown(Keys.Up)) Position.Y -= 10;
if (state.IsKeyDown(Keys.Down)) Position.Y += 10;
if (state.IsKeyDown(Keys.Left)) Position.X -= 10;
if (state.IsKeyDown(Keys.Right)) Position.X += 10;
base.Update(gameTime);
}
直接將 Position 設為滑鼠座標會瞬間傳送,缺乏過渡。真實遊戲地圖含障礙物,需尋路。本範例使用 Franco, Gustavo 的 A* 函式庫 (PathFinderFast)。
byte[,] m_matrix = new byte[1024, 1024];
for (int y = 0; y < m_matrix.GetUpperBound(1); y++)
for (int x = 0; x < m_matrix.GetUpperBound(0); x++)
m_matrix[x, y] = 1;
MouseState ms = Mouse.GetState();
if (ms.LeftButton == ButtonState.Pressed)
{
var finder = new PathFinderFast(m_matrix);
finder.Formula = HeuristicFormula.Manhattan;
finder.SearchLimit = 2000;
m_path = finder.FindPath(
new Vector2((int)Position.X, (int)Position.Y),
new Vector2(ms.X, ms.Y));
}
if (m_path != null && m_path.Count > 0)
{
int idx = m_path.Count - 1;
Position = new Vector2(m_path[idx].X, m_path[idx].Y);
m_path.RemoveAt(idx);
return; // 本幀只移動一步
}
spriteBatch.Draw(img, new Rectangle((int)Position.X, (int)Position.Y, 50, 80), Color.White);
原始碼下載:WindowsGame2.rar