Game Development Reference
In-Depth Information
Fig. 19.1
An example of a
sheet of sprites (four columns
and two rows)
LoadContent
method, and we add the background sprite to it:
gameWorld =
new
GameObjectList();
gameWorld.Add(
new
SpriteGameObject("Sprites/spr_background_levelselect"));
We also add the penguin sprite to the game world, and position it somewhere in the
middle of the screen:
SpriteGameObject penguin =
new
SpriteGameObject("Sprites/spr_penguin@4x2", 1,
"penguin");
penguin.Position =
new
Vector2(500, 420);
gameWorld.Add(penguin);
19.3 Loading a Sprite Sheet
In the
Jewel Jam
game, a
SpriteGameObject
instance keeps a reference to the sprite,
which is represented by an object of type
Texture2D
. In order to deal with sprite
sheets, we are going to create a new class called
SpriteSheet
that we will use instead
of a
Texture2D
object directly. We will add specific functionality to this class that
allows us to maintain the number of rows and columns in the sheet and that can
select a different element of the sheet to be drawn.
In the previous section, you've probably seen that the name of the penguin sprite
('spr_penguin@4x2') is quite peculiar. The reason is that we are going to add a
nice trick to the
SpriteSheet
class that allows us to specify in the
file name
what the
dimensions of the sprite sheet are. In this case, the penguin sprite has four columns
and two rows. The
SpriteSheet
constructor then analyzes the name of the sprite and
determines the dimensions accordingly. There are three different possibilities:
•
the image is a single sprite: in that case, no definition is provided at the end of the
filename, an example is the sprite 'spr_wall.png';
•
the image is a strip of sprites: in that case, we provide a single integer number
behind the '@' sign, an example is the sprite 'spr_field@2.png';
•
the image is a sheet of sprites: both dimensions (columns times rows) are provided
in the filename, for example in 'spr_penguin@4x2.png'.
We are going to use the
Split
method from the
string
class to find out which possi-
bility we are dealing with. But before we do that, we need to declare a few member
variables for storing the sheet dimensions and the part of the sprite sheet that is