9. shapethefuture
電子工程系
應 用 電 子 組
電 腦 遊 戲 設 計 組
using System;
namespace WindowsGame1
{
#if WINDOWS || XBOX
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
using (Game1 game = new Game1()) //建立遊戲物件
{
game.Run(); //執行遊戲
}
}
}
#endif
}
Program.cs
9
12. shapethefuture
電子工程系
應 用 電 子 組
電 腦 遊 戲 設 計 組
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace WindowsGame1
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics; // 繪圖卡管理物件
SpriteBatch spriteBatch; // 2D圖形繪出物件
}
...
};
Game1.cs 1/5
12
引用XNA命名空間
14. shapethefuture
電子工程系
應 用 電 子 組
電 腦 遊 戲 設 計 組
/// <summary>
/// 資源載入作業,遊戲執行時LoadContent只會被執行一次
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
}
/// <summary>
/// 釋放資源作業,遊戲執行時UnloadContent只會被執行一次
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
Game1.cs 3/5
14
18. shapethefuture
電子工程系
應 用 電 子 組
電 腦 遊 戲 設 計 組
3. 修改Update(),當按下Esc鍵時結束程式
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
KeyboardState newState;
newState = Keyboard.GetState();
if (newState.IsKeyDown(Keys.Escape)) this.Exit(); // Esc鍵結束程式
// TODO: Add your update logic here
base.Update(gameTime);
}
4. 編譯執行XNALabI
實作練習(一) 2/2
18
19. shapethefuture
電子工程系
應 用 電 子 組
電 腦 遊 戲 設 計 組
1. 開啟XNALabI方案,將Cross4.png加到XNALabIContent
2. 在Game1類別新增資料成員,記錄顏色值及
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
byte R = 0, G = 0, B = 0; // 紅、綠、藍三原色初始色
Texture2D bg_frame;
…
}
3. 修改LoadContent(),載入圖檔資源
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
bg_frame = this.Content.Load<Texture2D>("Cross4"); // 載入底圖
}
實作練習(二) 1/3
19
20. shapethefuture
電子工程系
應 用 電 子 組
電 腦 遊 戲 設 計 組
4. 修改Update(),依據滑鼠游標位置設定顏色值
protected override void Update(GameTime gameTime)
{
…
// TODO: Add your update logic here
MouseState mouse = Mouse.GetState(); // 取得滑鼠狀態
if (mouse.X > graphics.PreferredBackBufferWidth / 2) // 超過螢幕寬的一半
R = 255;
else
R = 0;
if (mouse.Y > graphics.PreferredBackBufferHeight / 2) // 超過螢幕高的一半
G = 255;
else
G = 0;
base.Update(gameTime);
}
實作練習(二) 2/3
20