XNA-2D 打磚塊遊戲(三)- Components

XNA-2D 打磚塊遊戲(三)- Components

在一個遊戲裡,通常會用到很多重複的東西,像是分數、對話框等,另外也可能有很多需要抽換的東西,最常見的就是攝影機囉。

這類的東西都可以寫成component,一般我們可以繼承GameComponent或是DrawableGameComponent。

GameComponent比DrawableGameComponent少了IDrawable介面,其他都相同,所以這裡只介紹DrawableGameComponent。

我們就拿打磚塊遊戲當範例,增加分數的顯示,

首先設計一個專門顯示分數的物件ScoreUI,他繼承DrawableGameComponent之後,覆寫LoadContent、Draw、Update這三個函數,

其功能很簡單,就是將分數和生命顯示出來,程式碼如下:

    public class ScoreUI : DrawableGameComponent{
        public SpriteFont Font;
        public int Life;
        public int Score;

        private SpriteBatch spriteBatch;
        private Vector2 scoreVector = new Vector2(200, 5);
        private Vector2 scoreWordVector = new Vector2(150, 5);
        private string scoreWord = "Score:";
        private Vector2 lifeVector = new Vector2(50, 5);
        private Vector2 lifeWordVector = new Vector2(5, 5);
        private string lifeWord = "Life:";

        public ScoreUI(Game game)
            : base(game) {
            Font = game.Content.Load<SpriteFont>("SpriteFont1");
            Life = 3;
            Score = 0;
        }

        protected override void LoadContent() {
            spriteBatch = new SpriteBatch(GraphicsDevice);
        }

        public override void Update(GameTime gameTime) {

            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime) {

            spriteBatch.Begin();
            spriteBatch.DrawString(Font, scoreWord, scoreWordVector, Color.Red);
            spriteBatch.DrawString(Font, Score.ToString(), scoreVector, Color.Red);
            spriteBatch.DrawString(Font, lifeWord, lifeWordVector, Color.Red);
            spriteBatch.DrawString(Font, Life.ToString(), lifeVector, Color.Red);
            spriteBatch.End();
            
            base.Draw(gameTime);
        }
    }

之後我們在Game1的初始函式內,加上此Component:

 

protected override void Initialize() {
    // TODO: Add your initialization logic here
    Score = new ScoreUI(this);
    Components.Add(Score);
    base.Initialize();
}

之後在主程式裡,會依照加入Components的先後順序來呼叫LoadContent、Update、Draw等主要函式,

但是Update和Draw函式可以藉由DrawOrder以及UpdateOrder來改變順序,數字越小越先呼叫。

遊戲畫面如下:

image

範例檔:XNA-2D 打磚塊遊戲(三)- Components.rar