dimanche 8 mars 2009

Hello, our first component

Let's redo our "Hello World" game, but in another way.
This time will make an "Hello World" component.

This time, we will not directly code in our Game class, we will create a Component and simply use it in our game.

Create a XNA 3.0 Windows Game project from scratch with the wizard (let's name it HelloComponents), then add a a sprite font content to our project (like the steps 0 & 1 of the previous tutorial).

Step 1: Create our Hello World Component
To create our component:
  1. In our project in the solution explorer: Right click on our (HelloComponents)project node
  2. In the popup menu: Choose Add
  3. In the submenu: Choose New Item
  4. In the categories tree: Choose Visual C# Items/XNA Game Studio 3.0
  5. In the template list: Choose Game Component
  6. Rename our game component: For this tutorial, please, name your component 'HelloComponent'
  7. Then: Click on Add
By default new Game Component inherit from GameComponent class. This class is usable for us now, because it is not 'drawable'. So just change the base class of our component to DrawableGameComponent .

Step 2: Customize our component
We need 2 fields. One for the sprite font like in the previous tutorial and one for the sprite batch because in the previous tutorial we use the game's one, but the wizard does not add one in component.
SpriteBatch spriteBatch;
SpriteFont myFont;

Then we need to override two methods. First one to load the sprite font content and create the sprite batch. Second one to actually display the text.
protected override void LoadContent()
{
base.LoadContent();

spriteBatch = new SpriteBatch(GraphicsDevice);
myFont = Game.Content.Load<SpriteFont>("MyFont");
}


and
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);

spriteBatch.Begin();
spriteBatch.DrawString(myFont, "Hello components' World", Vector2.Zero, Color.Yellow);
spriteBatch.End();
}


Step 3: Add our component to our game
In our game class, in the Initialize method, just add a line:
protected override void Initialize()
{
Components.Add(new HelloComponent(this));
base.Initialize();
}


That's all.

Aucun commentaire:

Enregistrer un commentaire