HTML and CSS Reference
As you can see, it contains a number of 32×32 tiles that can be used in a game. We will
not create an entire game in this chapter, but we will examine how to use these tiles to
create a game screen. In Chapter 9 , we will create a simple maze-chase game using some
of these tiles.
Examining the Tile Sheet
The tile sheet is formatted into a series of tiles starting at the top left. As with a two-
dimensional array, the numbering starts at 0—we call this 0 relative . Moving from left
to right and down, each tile will be referenced by a single number index (as opposed
to a multidimensional index). The gray square in the top left is tile 0, while the tank at
the end of the first row (the rightmost tank) is tile 7. Moving down to the next row, the
first tank on the far left of the second row is tile 8, and so on until the final tile on row
3 (the fourth row down when we start numbering at 0) is tile 31. We have four rows
with eight columns each, making 32 tiles with indexes numbered 0 to 31.
Creating an Animation Array
Next, we are going to create an array to hold the tiles for the animation. There are two
tanks on the tile sheet: one is green and one is blue. Tiles 1‒8 are a series that—when
played in succession—will make it appear as though the green tank's tracks are moving.
Remember, the tile sheet starts at tile 0, but we want start with the first
tank image at tile number 1.
We will store the tile ids we want to play for the tank in an array:
var animationFrames = [1,2,3,4,5,6,7,8];
We will use a counter to keep track of the current index of this array:
var frameIndex = 0;
Choosing the Tile to Display
We will use the frameIndex of the animationFrames array to calculate the 32×32 source
rectangle from our tile sheet that we will copy to the canvas. First, we need to find the
x and y locations of the top-left corner for the tile we want to copy. To do this, we will
create local variables in our drawScreen() function on each iteration (frame) to calculate
the position on the tile sheet. The sourceX variable will contain the top-left corner x
position, and the sourceY variable will contain the top-left corner y position.