XNA 103 : Sprites
Words are great but unless you're going to rewrite classics like Hitchhikers or L.G.O.P. you're going to need the ability to draw something more interesting on screen. As before we'll start with a new project.
Before we go on you're going to need a sprite for the project so you can use any BMP/JPG/PNG/TGA or even a DDS file.
Here's the one I'll be using. I'm no artist so it's just a 5 minute job in paint.NET, and it shows. Just right click this image and select Save Image as... put it someplace you can find it, you're going to need it in a second.
Next we need to add the sprite to our Content Sub Project. Same as with adding a new font right click on the Content Sub Project then select Add, but this time select Existing Item...
When the Add Existing Item Dialog opens navigate to where you saved the sprite image, select it and click Add
Next we need somewhere to load the Sprite, for this we will need to add a new variable at the top of our class like this :-
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D sprite;// new sprite variable
.
.
.
The new object here is what XNA uses to store it's texture data or in this case a sprite. next we need to load it into the variable scroll down to LoadContent() and add the following:-
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Load the Texture2D into the variable
sprite = Content.Load<Texture2D>("Sprite001");
}
As you can see just like with loading the SpriteFont We've told Content.Load() that it's loading a Texture2D object and given it the asset name without the extension.
Now for the Draw() method :
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(sprite, new Vector2(100, 100), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
Again the same as with the font but this time we're calling the Draw() method which adds a sprite to the batch of sprites to be rendered, specifying our texture, the screen position and the color we want. Press F5 to compile and run the game.
Conclusion
As you can see there really isn't any difference between fonts and sprites except for the variable type and the methods used to draw them, now all we need is for us to be able to move our sprite.


