Game Development Reference
In-Depth Information
we can use it in all the methods. But what type should we give this variable? We
have only seen simple types such as int or float , and they represent a number, not an
image. Fortunately, the XNA game engine provides a type for storing sprites called
Texture2D . So, let us declare a variable of that type:
Texture2D balloon;
Loading a sprite is done using the method Load<Texture2D> from the Content class.
This method loads a sprite from a file and we can assign the loaded sprite to the
balloon variable (which is of type Texture2D ), as follows:
balloon = Content.Load<Texture2D>("spr_lives");
We now have declared and assigned a variable called balloon , which contains the
sprite loaded from the file 'spr_lives.png'. As you can see, we do not have to provide
the filename extension, the Load method automatically adds it for us.
4.3.4 Drawing Sprites
Loading a sprite and storing it in memory does not mean that the sprite is drawn on
the screen. For that to happen, we need to do something in the Draw method. Drawing
sprites can be done with the class SpriteBatch . But in order to use methods from that
class, we first need a variable of the type SpriteBatch . In the template project, this
work is already done for us. The variable is declared at the class body level and it is
givenavalueinthe LoadContent method:
spriteBatch = new SpriteBatch(GraphicsDevice);
As a parameter, we have to provide the graphics device (the same thing we used
to set the background color in the previous example). This is needed, because the
SpriteBatch class needs to know which graphics device it should use to draw the
sprites.
Before we draw anything on the screen, we clear it so that any things previously
drawn are removed. As usual, this is done by a simple call to the Clear method:
GraphicsDevice.Clear(Color.White);
Of course, you can choose any color here, or even use the code from the previous
example to let the background color vary according to the current time.
Drawing a sprite on the screen is done using the Draw method from the SpriteBatch
class, but before drawing anything, the class requires you to call the Begin method.
Similarly after you have finished drawing, you need to call the End method. This
means that drawing the balloon sprite on the screen consists of the following in-
structions:
 
Search WWH ::




Custom Search