HTML and CSS Reference

In-Depth Information

Here is pseudocode for the
sourceX
calculation:

sourceX = integer(current_frame_index modulo

the_number_columns_in_the_tilesheet) * tile_width

The modulo (%) operator will return the remainder of the division calculation. Below

is the actual code (with variables replaced with literals) we will use for this calculation:

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 will use for this calculation:

var sourceY = Math.floor(19 / 10) *32;

This works out to
y = 1*32 = 32;
. So, the top-left location on the
ship_tiles.png
from

which to start copying pixels is
288
,
32
.

To actually copy this to the canvas, we will 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 will use to render the player ship. It will replace the
render

Player()
function in
Example 8-12
in
Chapter 8
:

function renderPlayerShip(x,y,rotation, scale) {

//transformation

context.save(); //save current state in stack

context.globalAlpha = parseFloat(player.alpha);

var angleInRadians = rotation * Math.PI / 180;

var sourceX = Math.floor((player.rotation/10) % 10) * 32;

var sourceY = Math.floor((player.rotation/10) /10) *32;

if (player.thrust){

context.drawImage(shipTiles2, sourceX, sourceY, 32, 32,

player.x,player.y,32,32);

}else{

context.drawImage(shipTiles, sourceX, sourceY, 32, 32,

player.x,player.y,32,32);

}

//restore context

context.restore(); //pop old state on to screen

context.globalAlpha = 1;

}