domingo, 20 de fevereiro de 2011

XNA Adventures: Building a Sprite Class

Hi everybody!
After some time playing with XNA I decided to start spreading what I know so others don't need to suffer in some problems and can enjoy as much or even more than I'm enjoying play with it.
In this first tutorial I'll show you something very basic that is a simple base Sprite class that you can expand or use in any project (I'll use it in my next tutorial to show 2D animation).

Visual Studio 2010 or 2008; (I'm using VS2010)
XNA 4.0 or 3.x; (I'm using 4.0 so somethings might need changes, just ask me if you got any problems ok?)
Start by creating a new windows game project in visual studio then create a new class named Sprite. This class will be the base for any sprite (i.e. char sprite, life sprite, background and so on) that you create so don't add any specific logic here.

A sprite needs a texture (the image), a position, a size, a scale and his asset name. Let's add them as attributes

The properties are now in their place but we don't set any of them, we're going to do this using two methods: Rescale and LoadContent
-Rescale: This method will verify if the texture exists and then will rescale the image trough Size property; -LoadContent: This method will load our texture and rescale the image properly calling Rescale.

Ok almost there, we just need to draw our sprite and update it so it'll be prepared to future movement input.
To achieve that we will add two drawing methods and one update method.
-Draw: Use a SpriteBatch.Draw method to draw our texture in the screen;
-Update: Change position using sprite speed and direction and the game time.
The drawing method should be like this

Basically the parameters we're passing to SpriteBatch.Draw are:
-Texture: _spriteTexture;
-Position: Position;
-SourceRectangle: sourceRectangle; This represents the area of your image that actually will be draw to the screen, everything that is not inside this rectangle will be ignored.
-Color: Color.White; This is the a color to tint your sprite. Use white if you don't want to add any color layer to your image.
-Rotation: 0.0f;
-Origin:Your sprite origin, in this case it will be upper-left corner (0,0).
-SpriteEffects: flip your image here or use none;
-LayerDepth: xna draw textures in layers, use 0 so xna organize the layers or specify a number to set your texture layer;
To finish our Sprite class we only need an update method

From here you can change and adapt it as you desire.
If you just want to test it go on and change your Game class with the following code

That's it guys!

Nenhum comentário: