In game development, a “sprite” is simply a 2D image place somewhere on the screen. They generally make up the majority of a 2D game, and in a 3D game they may be used for the targeting reticule, the heads up display, etc. We are going to create a simple Sprite class that will handle drawing an image on screen. We will improve this class later on by allowing it to rotate, change size, etc. The basic Sprite class is written as follows:
public class Sprite : Component
{
Texture2D spriteTexture;
string filename;
Vector2 position = Vector2.Zero;
public float X
{
get { return position.X; }
set { position.X = value; }
}
public float Y
{
get { return position.Y; }
set { position.Y = value; }
}
public int Width { get { return spriteTexture.Width; } }
public int Height { get { return spriteTexture.Height; } }
public Sprite(float x, float y, string filename)
{
this.position = new Vector2(x, y);
this.filename = filename;
}
protected override void Load()
{
spriteTexture = Parent.Engine.Content.Load<Texture2D>(filename);
}
public override void Draw()
{
Parent.Engine.SpriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.None);
Parent.Engine.SpriteBatch.Draw(spriteTexture, position, Color.White);
Parent.Engine.SpriteBatch.End();
// Set back certain render states that are changed by the SpriteBatch
// that interfere with 3D rendering
resetRenderStates();
}
private void resetRenderStates()
{
Parent.Engine.GraphicsDevice.RenderState.DepthBufferEnable = true;
Parent.Engine.GraphicsDevice.RenderState.AlphaBlendEnable = false;
Parent.Engine.GraphicsDevice.RenderState.AlphaTestEnable = false;
}
}
Let’s try our new Sprite class out. Because we all need more puppies in our lives, we will draw the following onto the screen:

Save the picture, and drag it into the “Content” directory of your demo game project. We can then modify the Game1 class to create a new instance of the engine, load up a game screen, and create a sprite.

public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
Engine engine;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
}
protected override void LoadContent()
{
engine = new Engine(graphics);
GameScreen screen = new GameScreen();
engine.PushGameScreen(screen);
Sprite sprite = new Sprite(10, 10, "Content/puppy");
screen.AddComponent(sprite);
}
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
engine.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
engine.Draw(gameTime);
base.Draw(gameTime);
}
}


Its interesting I was getting impatient on the updates and I already wrote my own sprite class and I used it to create my menu buttons. But I’m glad you did this because you got some good features here I missed out.
I have read that it’s better to draw all sprites between single Spritebatch.Begin(); and Spritebatch.End(); not to call them for each sprite…
I was also under the impression that it’s not a good idea to have many objects in your game created as game components, though there’s never any really detailed discussion as to why? Why is this?
Presumably this is because of ‘hidden implementation’ details on how the XNA framework goes about handling components? Isn’t making all your sprite objects inherit from component therefore breaking this rule?
I too have heard that you should pass the graphics card as many sprites as possible between a Begin() and End() pair of a SpriteBatch – hence the word batch? I kind of get this because the graphics card is designed to work fastest on large amounts of data in one go without it’s state being disturbed. Having lots of Begin() – End() switching between every different sprite would therefore cause lots of graphics card state changes.
However, I’m new to this blog and this post is the first I’ve seen. From the code shown above, I’m not sure where JC is seeing that Begin() and End() will be called for each sprite? I’ll be checking out the blog in chronological order though so I assume JC is basing his assumption on his knowledge of previous posts covering the engine structure.
Good work on this blog series. Engine structure discussions are valuable even to beginners like me and I’m wondering why it’s not a prominent topic everywhere.
The XNA component system was designed with large amounts of objects in mind. If it was going to be a problem, the XNA developers would have implemented it differently. Generally you should avoid believing such strong “rules” when it comes to programming, as they’re generally not correct.
In addition, in this case, we’re not actually using the XNA component system, but the one built into our game engine.
You’re all correct that it would be best to call Begin(), draw all the sprites, then call End(), however as these are all individual objects that can draw at any point in the draw cycle, we have no way of knowing when we have drawn all the sprites we want to draw and when to start and stop the sprite batch. We may come up with something later on but for now, it’s too much of a performance hit.
For game screens that contain only 2D components/sprites you can call Begin();, then draw all sprites contained in this screen, then call End();.
That way you can also easily implement 2D camera and apply it’s transform matrix to all sprites in game screen – and reset renderstates once per screen, not after each sprite. IMO it’s better to keep 2D and 3D components in separate screens anyway.
If you use Save the State with the Sprite Batch you don’t need to reset it to how it was before. Reseting them like that isn’t needed.
Also with the Drawing of the Sprites, should go with the GameScreen, so while there will still be more than one.
Actually it’s recommended that you not use the save state mode feature. Instead of setting back the few states that we actually need set certain ways, it will first copy the state of all the render states that it changes, do the drawing, then set them all back. While convenient, the reading and writing of large numbers of render states is very slow and can actually affect performance. From Microsoft’s documentation (http://msdn.microsoft.com/en-us/library/bb195102.aspx):
“If Begin is called with SaveStateMode set to None, the caller must reset these states must be reset if they are used elsewhere. Calling Begin with SaveStateMode set to SaveState will reset these values properly, but performance may be adversely affected.”
“That way you can also easily implement 2D camera and apply it’s transform matrix to all sprites in game screen – and reset renderstates once per screen, not after each sprite. IMO it’s better to keep 2D and 3D components in separate screens anyway.”
I agree, and also we could implement our Deferred Renderer much more easy, why instead drawing the components on the fly we dont cache them on a variable component3D and component2D to draw in a draw manager class so we can easly change order of why layer we want to render and make a Forward renderer or Defered renderer as convenint? I think it will be easly to manage alphas and UI
Hey Sean, great tutorials, keep up the good work. I’m sure you’ve already read Shawn Hargreaves posts on SpriteBatch usage but seeing as it’s been mentioned here I thought I’d post the links as they are an essential read:
http://blogs.msdn.com/shawnhar/archive/2006/12/13/spritebatch-and-spritesortmode.aspx
http://blogs.msdn.com/shawnhar/archive/2006/12/14/spritebatch-sorting-part-2.aspx
http://blogs.msdn.com/shawnhar/archive/2006/12/14/return-of-the-spritebatch-sorting-part-3.aspx
Hey guys, I suck at programming in c# and am learning everything I can from these tutorials. I have learned so much already, except how to handle these null reference exceptions. The error I am getting right now is pointing me to the sprite.cs:
“Parent.Engine.SpriteBatch.Draw(spriteTexture, position, Color.White);”
I know that the error is somewhere else, but I cannot find where! Help please.
Wow. Nevermind, I found the error. It was on the GameScreen.cs. I never added Component.LoadComponent(); to the GameScreen.cs.
Hey, just wanted to say thanks for the tutorials. I really like the structured way of doing things.