# How to handle a Sprite Class?

Currently I am learning XNA and while playing around with some tutorials knowing what I am aiming for a game it made me think that the Sprite Class will be something very important and re-used a lot of times, not sure if I am mistaken or not with this thinking.

Bellow you can see the Sprite code I am using at the momment and I was wondering:

• How a Sprite Class should be or what functions in general it should have or am I mistaken that the Sprite Class will not be used by every sprite in my game ?

For example, in my sprite I could hold all property of the sprite even if one property is not being used, let's say an object that does not move around so it would have no speed which I could simple have a property saying that speed is disabled.

So i guess my real question is:

• How should I structure my Sprite Class to have the best usage out of it ?

If you have a sample code to show I would appreciate aswell not really necessary, just for reference (also it doesnt need to be in c#).

Hope my question is not too confusing.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace MyGameTest
{
class Sprite
{
public string AssetName;

public Rectangle Size;

private float mScale = 1.0f;

public Vector2 Position = new Vector2(0, 0);

public Vector2 Speed = new Vector2(0, 0);

private Texture2D mSpriteTexture;

public float Scale
{
get { return mScale; }
set
{
mScale = value;
Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
}
}

public void LoadContent(ContentManager theContentManager, string theAssetName)
{
AssetName = theAssetName;
Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
}

public void Draw(SpriteBatch theSpriteBatch)
{
theSpriteBatch.Draw(mSpriteTexture, Position,
new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height),
Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0);
}
}
}

• Are you somewhat new to OOP concepts? Correct me if I'm wrong, but based on your question, it seems you might be lacking fundemental OOP concepts, which would help you answer your own question If so, let us know and we can refer you to sme good OOP documentation. If you're up on OOP, please try to re-word the question so that the bits you need help with are more clear. – Nate Sep 22 '10 at 5:00
• @Nate hi, i do know what OOP is but i am not sure at all if that is the case ... which is why i am asking for advice on how i should go about structuring the code to hold these things ... thanks. – Guapo Sep 22 '10 at 6:27
• Maybe the right approch would be a base class with sub classes inherit from it as for example player class, monster class etc or w/e – Guapo Sep 22 '10 at 7:02
• Yes, I think that is exactly the way to go. Your Sprite class should do "sprite" things. Location, Velocity, Direction, Texture, etc, and then your Player class should inherit from Sprite and extend it by having properties like HitPoints, MaxSpeed, AttackPower, etc... – Nate Sep 22 '10 at 17:24
• @Nate thanks for the input, i guess i got the general idea of how it should be, but was still looking forward to find a nice example code to look at ... if you are aware of any well-written code about this let me know please ;) – Guapo Sep 23 '10 at 10:08

I have found the concepts and examples in Johnathan Harbor's book VB Game Programming with Direct X to be very useful when writing XNA and older MDX code. The book is OLD, and its in Visual Basic 6, but his examples do use encapsulation (since vb6 didn't support inheritance) but they best illustrate the concept of building a basic 'system' through classes - I'd recommend browsing through it in the bookstore or library just to get some of the ideas: http://search.barnesandnoble.com/Visual-Basic-Game-Programming-with-DIRECTX/Jonathan-S-Harbour/e/9781931841252 -- Thats not to say there are not any of these concepts well demonstrated on line or by other authors, but I know and can vouche for the ones in this book.

(This started as a comment but became too long pretty quickly)

You're thinking ahead of yourself, trying to implement everything before you actually use it. You don't even know what your Sprite class needs to do! Why are you writing it then? Classes are meant to serve a purpose. You don't write them ahead of time; you write them as you need them.

Start by actually starting on your game. You'll reach a point where you need to use a Sprite class. So then make it (or use it as it currently is). When you run into something which needs to be in the Sprite class, add it. But stop what you're doing, don't try and write a do-everything Sprite class because you'll just end up with a bunch of unused features that waste your time and probably aren't tested or implemented right.

For example, right now. That entire class is unimplemented. There's no point to it until there is something using it, and once you start using it, it will be clear exactly what you need and don't need.

• That is not true, i am using that class on a PONG Clone that i made while learning XNA and what made me think this was because i was going to make several balls to spawn and raise the difficult etc... but just from having 3 sprites on the screen i already saw that i was using that class a lot or should i say relying on it a lot ... So you should have asked me if it was unimplemented or not before anwsering like this i belive, anyway thanks – Guapo Sep 22 '10 at 3:43
• I think the OP is just having difficulty deciding what bits of functionality go in which class. – Nate Sep 22 '10 at 4:59
• Don't do it until you need it might be a nice stock answer, but it doesn't seem helpful on this occasion. – Fuu Sep 22 '10 at 7:40
• I dunno, I guess I read the question differently. I re-read it and this still seems an appropriate answer, no matter how "stock" it may be. – Ricket Sep 22 '10 at 21:07
• I'm agreed with Ricket, which is unfortunate since it doesn't help the OP. I'm not really sure how to phrase "the class is as useful as you make it" better, though. For the OP, what do you need your Sprite to do? Do you need it to move? Then set up a situation that needs it moving, and add the functionality that makes sense for that situation. Later it may seem like that functionality needs to move to some other class, and that's no problem! – dash-tom-bang Sep 23 '10 at 22:22

Well, a sprite is just a texture with a scale and coordinate in space, there'll be hundreds or thousands of them if you're going to use animated sprites. You'll need something to handle sprite flipping ie another class that groups sprites for animation purposes and can flip between them accordingly?

Here is some basics from FlatRedBall and its wiki (source is closed though); consider having a base class that is positioned, ie that has x, y (possibly z), rotation, scale, velocity, acceleration and whatever positioned objects will need. Have the sprite class and other relevant classes inherit this. Then have another class for actual game characters (entities) that are also positioned, but can either contain or some way be grouped (IAttachable) with sprites. Game characters generally need state as well as a lot of other things like collision bounds.

• thanks for your input that is how i might go for it. I would appreciate very much if you know of any open source codes that i could take a look at aswell... i did saw some stuff from FlatRed that was available but not everything is open. – Guapo Sep 23 '10 at 10:01
• Sadly it's not open but after playing with it for a day or two the concepts and coding needed to re-implement it should be quite clear, and generally lead to at least a few aha's. The same could probably be said for any engine featuring digest sprite handling classes. – Oskar Duveborn Dec 25 '10 at 1:10
• Only problem with this is that sometimes a sprite is actually just part of a texture and not the whole texture. – Pharap Mar 12 '15 at 6:48

Speaking as somebody who has actually had a need to implement a sprite class for XNA, here's how I did it: First I took a look at SpriteBatch's draw function (the one with all argument specified):

public void Draw(Texture2D texture, Vector2 position,
Rectangle? sourceRectangle, Color color, float rotation,
Vector2 origin, Vector2 scale, SpriteEffects effects,
float layerDepth);


And then I made my sprite class have these members:

class Sprite
{
Texture2D texture;
Vector2 position;
Rectangle? sourceRectangle;
Color color;
float rotation;
Vector2 origin;
Vector2 scale;
SpriteEffects effects;
}


Notice the similarity? ;)

However I have a rather unusual reason for needing such a class. You probably don't really want one!

What you are doing in your code is storing information about the image you are drawing as data inside an object. But what would be far better is to express as much information as possible directly in the code. In other words, say you have a bouncing ball with a position and a velocity. Here's what your class might look like:

class Ball
{
Vector2 position, velocity;

// Texture is a special case because the data cannot be expressed as code
Texture2D texture;

{
// But the name of the texture can be!
}

public void Draw(SpriteBatch sb)
{
sb.Draw(texture, position, null, Color.Red, 0,
new Vector2(texture.Width/2f, texture.Height/2f),
Vector2.One, SpriteEffects.None, 0f);
}
}


Note how as much information as possible about drawing the object is simply "hard coded". You should always have a preference for doing this, and make it data-driven only when absolutely necessary.

• I disagree, I would suggest that your Ball class inherit from your Sprite class, and use all of the Sprite fields in the Ball's Draw method. This gives you the ebst of both worlds with minimal extra code. Obviously if you have 100s of thousands of these, the extra weight of each Ball having a Sprite may have some performance implications. – Nate Sep 22 '10 at 17:23
• @Nate - I am going to very much disagree with your disagreement. Performance aside, pretty much every object in your game is likely to draw differently. Some might need multiple sprites, for example. Others might require animation. Others might require particle systems or animation or anything else! -- In my answer I've shown that the sb.Draw call is the same as or better than having a Sprite member. By inheriting from Sprite you've got all the disadvantages of having a member - and you're limited to just one (plus the other constraints it puts on your hierarchy). – Andrew Russell Sep 22 '10 at 23:08
• (In terms of what you should actually do - Ball should implement IDrawable or derive from DrawableGameComponent or a similar class. Or you could get fancy and implement something like cowboyprogramming.com/2007/01/05/evolve-your-heirachy/.) – Andrew Russell Sep 22 '10 at 23:14