Optimizing Code – Setting the Stage

Spent a couple of hours struggling to optimize my code tonight, but after some trial and error I’ve had some success.  Being more familiar with C# would have made this a lot easier, but that will come with time.

Basically, what I’ve been working on is getting the “behind the scenes” code set up so that I can start work on the game proper.  First thing I did was create a custom class called GameObject.  This object basically stores a texture for a Sprite, its gameworld coordinates, its rotation, and everything else that a Sprite will need to have in my first test game.

More importantly than anything else, it’s going to give me a reusable member method/function that will handle all of the messy parameter-passing behind the scenes so that my main Game class can stay simple and easy to use.

For instance, if I wanted to render a Sprite of a GameObject instance on the screen from the Game class, here’s what the function call would look like:

spriteBatch.Draw(ExampleObject.Texture, ExampleObject.Position, null, Color.White, ExampleObject.Rotate, ExampleObject.Origin, ExampleObject.Scale, SpriteEffects.None, 0.0f);

I would have to type this EVERY time I want to draw a texture or sprite to the screen!  No thanks…

In order to pare down that mess that the XNA Framework provided to me, I added this member method to the GameObject class:

public void Render(SpriteBatch objectBatch)

objectBatch.Draw(Texture, Position, null, Color.White, Rotate, Origin, Scale, SpriteEffects.None, 0.0f);


Ok, that’s a little bit cleaner, but not very impressive yet. Well, actually this is a recursive method. I wrote it once, and unless I need to change it, I’ll never touch it or type it again. The real help it gives me is changing that ultra long function that I typed way up there into this:


Yeah, I’ll take this over that monster function any day.

Small step that was made a lot harder due to my lack of familiarity with C# and the XNA Gamestudio, but considering I could recycle this method into every game I make, it’ll be worth it.

One potential problem I can see with this is that creating an extra spriteBatch every time I draw a sprite may be a waste or resources, and or be problematic for system performance.  I’ll have to do some research on what exactly a spriteBatch really is….


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: