Game Development Reference
In-Depth Information
14.2.2 Using a Grid to Draw Sprites
In Chap.
12
, we have seen how we can create a two-dimensional array. Now let us
put this feature to use in our next example for creating a two-dimensional playing
field. The program
JewelJam2
contains the instructions to create a game world con-
sisting of a grid of sprites that can be manipulated. Because there will only be three
different sprites in this example, we do not store the actual sprites in the grid, but an
integer that represents them
. We load these three sprites in the
LoadContent
method:
jewel1 = Content.Load<Texture2D>("spr_single_jewel1");
jewel2 = Content.Load<Texture2D>("spr_single_jewel2");
jewel3 = Content.Load<Texture2D>("spr_single_jewel3");
We also initialize the two-dimensional grid and assign random integer values in the
domain
[
0
,
2
]
to them:
grid =
new int
[5, 10];
for
(
int
x = 0; x < 5; x++)
for
(
int
y = 0; y < 10; y++)
grid[x, y] = random.Next(3);
As you can see, we use a
nested
for
-loop to initialize all the items in the array to a
random value. The outer
for
-loop traverses the different
x
-indices, while the inner
for
-loop traverses the
y
-indices. If you do not yet feel familiar with these kinds of
loops, try to follow step-by-step what is happening in this code fragment. We can
use the same nested
for
-loop in the
Draw
method to draw the sprites on the screen:
for
(
int
x = 0; x < 5; x++)
for
(
int
y = 0; y < 10; y++)
{
∗
∗
Vector2 position =
new
Vector2(85 + x
85, 150 + y
85);
if
(grid[x, y] == 0)
spriteBatch.Draw(jewel1, position, Color.White);
else if
(grid[x, y] == 1)
spriteBatch.Draw(jewel2, position, Color.White);
else
spriteBatch.Draw(jewel3, position, Color.White);
} spriteBatch.Draw(symbol3, position, Color.White);
In this code, you can see the advantage of using a grid. By using the indices, we can
calculate the position of the sprite in a very convenient way. The whole grid should
be drawn at an offset of
(
85
,
150
)
, so we add 100 to both the
x
and
y
values of
the local
position
variable. In order to calculate the actual position of the sprite, we
multiply the indices by 85 (which is the width and height of the sprite) to get the
final position. Finally, we determine which sprite to draw (
jewel1
,
jewel2
or
jewel3
)
by using an
if
-instruction to link the integer value in the grid to the sprite drawing
method.