Game Development Reference
In-Depth Information
You also add a parameter to the
drawImage
method that lets you specify the angle at which the object
should be rotated. This is what the new version of the
drawImage
method looks like:
Game.drawImage = function (sprite, position, rotation, origin) {
Game.canvasContext.save();
Game.canvasContext.translate(position.x, position.y);
Game.canvasContext.rotate(rotation);
Game.canvasContext.drawImage(sprite, 0, 0, sprite.width, sprite.height,
-origin.x, -origin.y, sprite.width, sprite.height);
Game.canvasContext.restore();
};
In the
start
method, you load the two sprites:
Game.backgroundSprite = new Image();
Game.backgroundSprite.src = "spr_background.jpg";
Game.cannonBarrelSprite = new Image();
Game.cannonBarrelSprite.src = "spr_cannon_barrel.png";
The next step is implementing the methods in the game loop. Until now, the
update
method has
always been empty. Now you have a good reason to use it. In the
update
method, you update the
game world, which in this case means you calculate the angle at which the cannon barrel should be
drawn. How do you calculate this? Have a look at Figure
5-5
.
opposite
angle
adjacent
© Springer-Verlag Berlin Heidelberg 2013
Figure 5-5.
Calculating the angle of the barrel based on the mouse pointer position
If you remember your math classes, you may recall that angles in triangles can be calculated with
trigonometric functions. In this case, you can calculate the angle using the tangent function, which is
given as follows:
tanangle =
opposite
adjacent
( )
In other words, the angle is given by
æ
è
ç
opposite
adjacent
ö
ø
÷
angle=arctan
Search WWH ::
Custom Search