mort8088 Just another WordPress site

6Mar/11Off

XNA 4.0 – Tutorial 2 – Sprites


Originally posted 2009 - Drawing a single static sprite on screen, also covered is adding existing files to the content pipeline. I've updated things to reflect using VS-2010 and XNA 4.0

 

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 :-

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:-

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 :

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.

Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.