HTML and CSS Reference
In-Depth Information
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.
for (var rowCtr=0;rowCtr<mapRows;rowCtr++) {
for (var colCtr=0;colCtr<mapCols;colCtr++){
var tileId = tileMap[rowCtr][colCtr]+mapIndexOffset;
var sourceX = Math.floor(tileId % 8) *32;
var sourceY = Math.floor(tileId / 8) *32;
context.drawImage(tileSheet, sourceX,
sourceY,32,32,colCtr*32,rowCtr*32,32,32);
}
}
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 values 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
previous examples. This time, though, we find the tileId using the [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 values that are easier to work with. Example 4-10 shows this concept in
action, and Figure 4-10 illustrates the results.
Example 4-10. Rotation, animation, and movement
var tileSheet = new Image();
tileSheet.src = "tanks_sheet.png";
var mapIndexOffset = -1;
var mapRows = 10;
var mapCols = 10;
var tileMap = [
[32,31,31,31,1,31,31,31,31,32]
, [1,1,1,1,1,1,1,1,1,1]
, [32,1,26,1,26,1,26,1,1,32]
, [32,26,1,1,26,1,1,26,1,32]
, [32,1,1,1,26,26,1,26,1,32]
, [32,1,1,26,1,1,1,26,1,32]
, [32,1,1,1,1,1,1,26,1,32]
, [1,1,26,1,26,1,26,1,1,1]
, [32,1,1,1,1,1,1,1,1,32]
Search WWH ::

Custom Search