HTML and CSS Reference
In-Depth Information
,
[ 32 , 31 , 31 , 31 , 1 , 31 , 31 , 31 , 31 , 32 ]
];
Displaying the map on the canvas
When we display the tile map, we simply loop through the rows in the tileMap array, and
then loop through the columns in each row. The tileID number at [row][column] will be
the tile to copy from the tile sheet to the canvas. row *32 will be the y location to place the
tile on the canvas; col *32 will be the x location to place the tile:
for
for ( var
var rowCtr = 0 ; rowCtr < mapRows ; rowCtr ++ ) {
for
for ( var
var colCtr = 0 ; colCtr < mapCols ; colCtr ++ ){
var
var tileId = tileMap [ rowCtr ][ colCtr ] + mapIndexOffset ;
var
var sourceX = Math . floor ( tileId % 8 ) * 32 ;
var
var sourceY = Math . floor ( tileId / 8 ) * 32 ;
context . drawImage ( tileSheet , sourceX ,
sourceY , 32 , 32 , colCtr * 32 , rowCtr * 32 , 32 , 32 );
}
}
NOTE
The row, column referencing might seem slightly confusing because row is the y direction and
column is the x direction. We do this because our tiles are organized into a two-dimensional array.
The row is always the first subscript when accessing a 2D array.
We use the mapRows and the mapCols variables to loop through the data and to paint it to the
canvas. This makes it relatively simple to modify the height and width of the tile map without
having to find the hardcoded values in the code. We could have also done this with other val-
ues, such as the tile width and height, as well as the number of tiles per row in the tile sheet
(8).
The sourceX and sourceY values for the tile to copy are found in the same way as in the pre-
viousexamples.However,thistimewefindthe tileId byusingthe [rowCtr][colCtr] two-
dimensional lookup and then adding the mapIndexOffset . The offset is a negative number
( −1 ), so this effectively subtracts 1 from each tile map value, resulting in 0-relative map val-
ues that are easier to work with. Example 4-10 shows this concept in action, and Figure 4-10
illustrates the results.
Search WWH ::




Custom Search