HTML and CSS Reference
In-Depth Information
The modulo (%) operator returns the remainder of the division calculation. Following is the
actual code (with variables replaced with literals) we use for this calculation:
var
var sourceX = Math . floor ( 19 % 10 ) * 32 ;
The result is x = 9*32 = 288; .
The calculation for the sourceY value is similar, except we divide rather than use the modulo
operator:
sourceY = integer ( current_frame_index divided by
the_number_columns_in_the_tilesheet ) * tile_height
Here's the actual code we use for this calculation:
var
var sourceY = Math . floor ( 19 / 10 ) * 32 ;
Thisworksoutto y = 1*32 = 32; .Therefore,thetop-leftlocationonthe ship_tiles.png from
which to start copying pixels is 288 , 32 .
To copy this to the canvas, we use this statement:
context . drawImage ( shipTiles , sourceX , sourceY , 32 , 32 , player . x , player . y , 32 , 32 );
In Chapter 8 , we needed quite a lot of code to draw and translate the player ship at the current
rotation. When we use a tile sheet, this code is reduced considerably.
Here is the code we use to render the player ship. It replaces the renderPlayer() function in
Example 8-12 in Chapter 8 :
function
function renderPlayerShip ( x , y , rotation , scale ) {
//transformation
context . save (); //save current state in stack
context . globalAlpha = parseFloat ( player . alpha );
var
var angleInRadians = rotation * Math . PI / 180 ;
var
var sourceX = Math . floor (( player . rotation / 10 ) % 10 ) * 32 ;
var
var sourceY = Math . floor (( player . rotation / 10 ) / 10 ) * 32 ;
iif ( player . thrust ){
context . drawImage ( shipTiles2 , sourceX , sourceY , 32 , 32 ,
player . x , player . y , 32 , 32 );
} else
else {
context . drawImage ( shipTiles , sourceX , sourceY , 32 , 32 ,
player . x , player . y , 32 , 32 );
}
//restore context
context . restore (); //pop old state on to screen
Search WWH ::




Custom Search