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:
- In our project in the solution explorer: Right click on our (HelloComponents)project node
- In the popup menu: Choose Add
- In the submenu: Choose New Item
- In the categories tree: Choose Visual C# Items/XNA Game Studio 3.0
- In the template list: Choose Game Component
- Rename our game component: For this tutorial, please, name your component 'HelloComponent'
- Then: Click on Add
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;
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");
}
{
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();
}
{
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();
}
{
Components.Add(new HelloComponent(this));
base.Initialize();
}
That's all.
Aucun commentaire:
Enregistrer un commentaire