// you’re reading...

Sprites

How to Add a Sprite in XNA Game Studio Express

There are two commonly accepted definitions of a sprite: one is the refreshingly crisp soft drink that was released in 1961 by the Coca-Cola Company. To the rest of us (and XNA developers in particular) a sprite is just a simple 2D in-game graphic.

Although sprites commonly appear 3D, they are actually 2D images- which have led some of them to be cleverly referred to as 2.5D. Sprites are essentially the basis of all 2D games; and make up particle systems, text, and heads-up displays in 3D games. Since the sprite is the building block of most games, what better place is there to start learning XNA Game Studio Express?

Lost? View the previous section: Getting Started with Making Games in XNA Game Studio Express

How Sprites Function within XNA Game Studio Express

There are three basic terms associated with sprites XNA: textures, the sprite itself, and the Sprite Batch.

A texture and sprite are very similar in definition. A texture is a digital image that remains in-memory, and is represented by an array of colored pixels. This is just a lot of fancy wording for something as simple as a wood texture you may use to make a rectangle look like a board.

Sprites are two-dimensional images that can act as textures, but normally have a certain purpose in the game. You will see sprites commonly used for characters, objects (such as trees), enemies, or even tools such as weapons.

The Sprite Batch is a class that draws ours sprites onto the screen. This class can work with groups of sprites while applying the same settings to all of them. This class is necessary to get the sprite onto the screen- so we’ll review this in more detail further on.

Before we get any further into creating and animating our own sprite, let’s do a little review on the XNAGame Studio Express interface and syntax.

Finding Your Way around XNA Game Studio Express

Now that we have the theory (hopefully) in memory, we can move onto opening XNA Game Studio Express. You will want to start a new Windows Game project by selecting File and then New Project. You should see a screen similar to the one below.

You can name the project whatever you would like, but make sure that you select Windows Game. Also make note of where you store the project. By default, this will be the Projects folder in Visual Studio 2005.

You’ll see a code template filled with vibrant green and blue colors. This template is necessary for game operation, so do not erase anything unless you know what you are doing. While we won’t dwell on the specifics of what each code block does at this point, a few things should be noted.

First, the green text is what is called a comment. Comments are not parsed by the game engine- they are only for the developer to make references and reminders in the code. Comments in XNA Game Studio Express are created with two backslashes (“//”). Multi-line comments can be made starting with /* and ending with */.

Comment Syntax in XNA Game Studio Express

// This is my very own comment!

/* this is

* a longer

* comment! */

Also note that XNA Game Studio Express uses blue and other colored texts for certain commands. This is merely to help organize data- there is no other significance of this color coding. You will notice that classes, for instance, are dark blue- while other structures are lighter blue.

An Example of Code Highlighting

public Game1()

{

graphics = new GraphicsDeviceManager(this);

content = new ContentManager(Services);

}

Before we get to the sprite aspects of XNA, we need to learn one more thing: how the four basic methods that XNA created for us actually work!

How Do The Methods in XNA Game Studio Express Work?

There are four methods that were created for us: LoadGraphicsContent, Update, Draw, and UnloadGraphicsContent. These four methods act as the heartbeat of an XNA game- so be prepared to memorize what they do and how.

LoadGraphicsContent is a method that is somewhat explanatory. Any images or other media files that you upload via the Content Pipeline will be called to here. This will load the media into memory, making it ready for use in the game you have created. Below is an example of calling to a media file (something we will actually learn further on).

An Example of The XNA LoadGraphicsContent Method

protected override void LoadGraphicsContent(bool loadAllContent)

{

if (loadAllContent)

{

// TODO: Load any ResourceManagementMode.Automatic content

//Load Sprite Batch *XNAGameDev.com

spriteBatch = new SpriteBatch(this.graphics.GraphicsDevice);

//Load The Image *XNAGameDev.com

MainCharacter = contentLoader.Load<Texture2D>(“Sprites\\Main_Character”) as Texture2D;

}

// TODO: Load any ResourceManagementMode.Manual content

Note the above example will not work until we learn more about sprites- but you get the general idea how sprites and textures are loaded via the LoadGraphicsContent method! Simply replace the Sprites\\Main_character with the image filename you have, and voila; you have successfully referenced your sprite!

The Update method is where most of the action takes place. This is where the “game loop” as it is called operates. If you have an objects that need to be updated (check to see if a key was pressed, for instance) they will have to be referenced here. This method updates once every frame- before the graphics are drawn to the screen. Below is an example of how we find out if a key was pressed or not (something we will not cover until later- but it’s good to see the power of XNA!).

An Example of The XNA Update Method

protected override void Update(GameTime gameTime)

{

// Allows the game to exit

if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

this.Exit();

// TODO: Add your update logic here

//If the UP key is pressed, move the player up! *XNAGameDev.com

if (ksKeyboardState.IsKeyDown(Keys.Up))

{

Move_Player_Up = true;

}

The Draw method is for the process of drawing the graphics onto the screen. With every single frame, the screen is redrawn from the bottom up. In the below example, we see how we might call to several different functions to draw multiple sprites with the same Sprite Batch.

An Example of The XNA Draw Method

protected override void Draw(GameTime gameTime)

{

graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

// TODO: Add your drawing code here

spriteBatch.Begin()

DrawPlayer(spriteBatch);

DrawBackground(spriteBatch);

DrawEnemies(spriteBatch);

spriteBatch.End()

base.Draw(gameTime);

}

Lastly, we need to unload any resources we have with UnloadGraphicsContent. This method will free up resources for us, so it’s important to unload any graphics you create. In most cases you could simply dispose of the Content Manager itself. If you manually managed resources (which we won’t be doing in our example) you will need to unload them separately. Below you can see how simple it is to unload everything by disposing of the Content Manager with content.Unload();.

An Example of The XNA UnloadGraphicsContent Method

protected override void UnloadGraphicsContent(bool unloadAllContent)

{

if (unloadAllContent)

{

// TODO: Unload any ResourceManagementMode.Automatic content

content.Unload();

}

// TODO: Unload any ResourceManagementMode.Manual content

}

If you’re eager to get to the sprite animation, don’t worry- it’s coming up next!

How to Add a Sprite in XNA Game Studio Express

First you will want to create a new project- we called ours WindowsGame3. The first thing we should do is declare our Sprite Batch and texture. Look at the following code; we place the new lines directly after the class declaration for WindowsGame3.

Declaring Sprite Batch and The Texture Variable

//Make Our Sprite Batch *XNAGameDev.com

protected SpriteBatch s_batch = null;

//Load Character Texture *XNAGameDev.com

protected Texture2D texture_mcharacter = null;

It’s usually a good idea to assign objects to the state of null, since we want to make sure we know what the object is holding. (In some cases, the absence of null may fill a variable with garbage that could crash our game.) And in case you are wondering what our texture_mcharacter is, we are using a certain JPG image that you may remember form videogame past. You may download the image pictured below and use it in your own project.

To add the handsomely ripped Ryu to your project, simply go to Project and choose Add Existing Item.

In the screen that comes up, find the image you want to use for the sprite animation. Be sure to select “All Files,” “Content Pipeline Files,” or “Image Files” for the file type, or you may not see the image in the file view. To avoid complications, make sure that your sprite file is named Sprite1- this is the name we use in our example.

Now that we have our declarations and image files in place, we need to reference the image files within the LoadGraphicsContent method.

Loading The Sprite Into The XNA Content Pipeline

protected override void LoadGraphicsContent(bool loadAllContent)

{

if (loadAllContent)

{

//Initialize Sprite Batch *XNAGameDev.com

m_batch = new SpriteBatch(graphics.GraphicsDevice);

//Load Textures *XNAGameDev.com

texture_mcharacter = content.Load<Texture2D>(@”sprite1″);

}

// TODO: Load any ResourceManagementMode.Manual content

}

The above method is rather simple. Just replace sprite1 with the media you uploaded via the Content Pipeline, and it’ll be loaded for further use! Next we should draw the sprite to the screen with the Draw method. The following code will do just that.

Using The XNA Draw Method to Output The Sprite To The Screen

protected override void Draw(GameTime gameTime)

{

graphics.GraphicsDevice.Clear(Color.White);

// TODO: Add your drawing code here

s_batch.Begin();

Vector2 loc = new Vector2(100, 100);

s_batch.Draw(texture_mcharacter, loc, Color.White);

s_batch.End();

base.Draw(gameTime);

}

The above code is rather simple once you get the hang of things. We have to begin the Sprite Batch, define the location, draw the sprite, and then end the Sprite Batch. In our example we drew the sprite at the location (100, 100)- you can use anything you’d like. Be sure to call the s_batch.end(); - try running the program without it and see what happens. (The error is confusing at first, but easily explained. Since each frame forces the Draw method to be called, the s_batch would begin more than once without an end- and that will result in an error!)

Notice that the graphics.GraphicsDevice.Clear(Color.White); line was changed from the default blue color. If we had kept the blue color, the whitespace in our image would show (and it isn’t pretty). In the future, we could use transparency to make the image look great on all backgrounds- but we will save that for a later day!

If all has gone well at this point, you should see something like the window below.

It couldn’t be more boring could it? Our rugged little fighter Ryu can’t punch, move, talk, or even blink! There is no environment, physics, lighting, or anything at all. But what we did accomplish is grasp the concept of a sprite.

So where do we go from here? We can add tint, transparency, animate, scale, and add all sorts of effects to the sprite. We could give the player the ability to move the character- and even make it jump!

All this (and more!) will be forthcoming in future sections.


View Full Source Code For This Tutorial: How to Add a Sprite in XNA Game Studio Express Source Code

View The Next Section: How to Tint Sprites in XNA Game Studio Express »

Tagged Under:
game design XNA Game Studio Exress XNA xbox programming xbox game development xbox 360 development pc game development C# game makers programming games online game development game development software 3d game development game programming tutorial computer game programming game develoment tools video game development
Tag Links:

Discussion

4 comments for “How to Add a Sprite in XNA Game Studio Express”

  1. Hey I like your tutorials, but some of the code doesn’t work for me and I don’t know why. I think for some reason, my XNA version is different than yours. Not but a lot, but just slight differences, such as:

    protected override void LoadContent
    as opposed to

    protected override void LoadGraphicsContent(bool loadAllContent)

    and what happens is when I try to copy and paste the code, I get about 8 errors that all say similar things, such as “Error 5 The name ’s_batch’ does not exist in the current context C:\Documents and Settings\Mike\My Documents\Visual Studio 2005\Projects\sprites\sprites\Game1.cs 93 13 sprites”

    I’m not sure what it means because I just started with XNA and c#.

    Do you know what is wrong? (I’m sorry to bother you, but I can’t figure this out)

    Email me back if you can please. Thanks

    Posted by mike | March 13, 2008, 5:41 pm
  2. Mike - Be sure to view the codeblock that contains
    “//Make Our Sprite Batch *XNAGameDev.com

    protected SpriteBatch s_batch = null;”

    It seems your error exists because you either have not declared your SpriteBatch variable or you have placed it in the wrong place.

    As for the rest of the errors, try leaving out the code above
    ” public class Game1 : Microsoft.Xna.Framework.Game
    {”

    As this can be version-specific code.

    Let me know how it goes, and you forgot to leave an email address, so leave that next time ;).

    Posted by admin | March 14, 2008, 10:26 am
  3. contentLoader hasn’t been set anywhere. So shouldn’t it be…

    MainCharacter = content.Load(“Sprites\\Main_Character”) as Texture2D;

    Instead of …

    MainCharacter = contentLoader.Load(“Sprites\\Main_Character”) as Texture2D;

    Posted by Skooter | April 7, 2008, 11:35 am
  4. Skooter- normally you would be right. But this was just an example of the code- this is NOT actually a part of the real source code.

    Good eye, though.

    Posted by admin | April 7, 2008, 7:39 pm

Post a comment