Game Development Reference
In-Depth Information
Fig. 15.1
The different jewels used in the game Jewel Jam
Fig. 15.1 for the image). The ordering of these jewels in the image file is important,
as we will show later on. Inside our object, we randomly choose which jewel we
represent by storing a random number between 0 and 26 (to cover the 27 varieties)
in a member variable variation . Therefore, the constructor becomes:
public Jewel( int layer = 0)
: base ("spr_jewels", layer)
{
variation = JewelJam.Random.Next(27);
}
Because the Jewel class knows which sprite it is going to use, we pass the string
(“spr_jewels”) directly to the base class constructor.
Now the only thing that needs to be modified is the Draw method, since we do
not want to draw the entire sprite, but only a part of it: the part that contains the
jewel that this object represents. For this, we use a more complicated version of the
Draw method in the SpriteBatch class that allows us to draw only part of a sprite. The
part that we want to draw is indicated by a Rectangle object. We can calculate the
position of this rectangle by using the value of the variation member variable:
sprite.Height, 0,
sprite.Height, sprite.Height);
Rectangle source = new Rectangle(variation
Here we assume that the segment we want to draw is a square shape that has the
same width and height as the height of the original sprite. The position of the rect-
angle (given by the first two parameters in the Rectangle constructor) is calculated by
multiplying the height of the sprite with the variation index. As a result, the higher
the variation index, the further to the right the rectangle is moved. Finally, a call to
the Draw method of the sprite batch shows the symbol on the screen:
spriteBatch.Draw(sprite, GlobalPosition, source, Color.White);
15.5 What You Have Learned
In this chapter, you have learned:
how to design an asset manager that is accessible from different classes;
how to create specific game object classes such as Jewel that use the asset man-
ager.
 
Search WWH ::




Custom Search