Game Development Reference
In-Depth Information
would be a completely opaque black background. The background layer will not change during
level play, so it will be copied a single time to the
canvasBitmapData
.
The code uses a nested loop structure to first loop through the rows of the
levelTileMap
array,
and inside that loop, it iterates through the columns in the array. Remember, this is opposite of
the
[x-axis], [y-axis]
special coordinate point systems. We do this because the rows of the 2D
array are the first subscript, and the columns are the second. Over the years, I have found it
much easier to work with 2D array data in rows and then columns, following the natural way an
array is accessed in Flash. In other words, I like to use
[row][column]
rather than trying to force
in a
[column][row]
style system.
Let's go through the code necessary to copy the data from our tile sheet to the
canvasBitmapData
in detail. The following lines are the most important piece of information in this chapter:
blitTile = levelTileMap[rowCtr][colCtr];
tileBlitRectangle.x = int(blitTile % tileSheet.tilesPerRow) * tileWidth;
tileBlitRectangle.y = int(blitTile / tileSheet.tilesPerRow) * tileHeight;
blitPoint.x=colCtr*tileHeight;
blitPoint.y = rowCtr * tileWidth;
canvasBitmapData.copyPixels(tileSheet.sourceBitmapData,
tileBlitRectangle, blitPoint);
This first line assigns the
blitTile
variable to hold the tile id from for the current [row][column]
cell in the level data. The id value corresponds to the array index in the single dimensional array
of tiles from the sheet (
tileSheetData
).
The
tileBlitRectangle
defines a square portion of the tile sheet to copy pixels from the tile
sheet.
The next two lines use a little math trick to find the starting
x
and
y
locations for the tile on the tile
sheet (the
tileBlitRectangle
's top-left corner). Since the sheet is actually 2D (eight columns by
four rows), and our array
(tileSheetData
) is only a single dimension, we need to use this trick.
The
x
value for the start of the tile to copy is the integer value (technically rounded down) of the
remainder
of the
blitTile
divided number of tiles in a row on the sheet. We use modulo (
%
)
operator rather than the division (
/
) operator to find this remainder value and cast it as an integer.
The
y
value for the start of the tile to copy is the integer value (technically rounded down) of the
blitTile
value using divided by the number of tiles in a row on the tile sheet.
See Figure 6-12 for a diagram of this concept.