XNA Framework 建構於 .NET Framework 2.0 之上,提供跨平台 (Windows/Xbox 360/Zune) 的 Managed 遊戲開發環境,封裝底層 DirectX 細節,大幅提升開發效率,適合 .NET 開發者入門遊戲程式設計。
每個 Game 衍生類別包含四個核心虛擬方法,形成訊息迴圈:
| 方法 | 用途 |
|---|---|
Initialize | 遊戲物件初始化 |
LoadContent | 載入圖片、音效、模型等資源 |
Update | 邏輯運算、輸入處理、物理模擬 (預設 60 FPS) |
Draw | 畫面繪製 |
old english sheepdog.png,Importer/Processor 設為 Texture - XNA Framework (編譯為 .xnb)。Texture2D img;,在 LoadContent 載入:img = Content.Load<Texture2D>("old english sheepdog");Draw 中繪製:spriteBatch.Begin();
spriteBatch.Draw(img, new Rectangle(0, 0, 50, 50), Color.White);
spriteBatch.End();
注意:所有 Draw 呼叫必須在 spriteBatch.Begin()/End() 之間,且一個 Game 只建議使用一個 SpriteBatch。
Point mousePos;
protected override void Update(GameTime gameTime)
{
MouseState ms = Mouse.GetState();
mousePos = new Point(ms.X, ms.Y);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
// ...
spriteBatch.Draw(img, new Rectangle(mousePos.X, mousePos.Y, 50, 50), Color.White);
// ...
}
或在 Initialize 設定 IsMouseVisible = true 直接使用系統游標。
Microsoft.Xna.Framework.Content.Pipeline 編譯為 .xnb 二進位格式。完成第一個 XNA 專案:載入貼圖、繪製至螢幕、處理滑鼠輸入。下一章將加入鍵盤控制與移動邏輯。