Game Development Reference
In-Depth Information
You can calculate the length of the opposite and adjacent sides by calculating the difference
between the current mouse position and the position of the cannon barrel, as follows:
var opposite = Game.mousePosition.y - Game.cannonPosition.y;
var adjacent = Game.mousePosition.x - Game.cannonPosition.x;
Now you have to calculate the arctangent using these values. How do you do this? Fortunately,
JavaScript knows a Math object that can help. The Math object contains a number of useful mathematical
functions, including trigonometric functions such as sine, cosine, and tangent, and their inverses
arcsine, arccosine, and arctangent. Two functions in the Math object calculate the arctangent. The first
version takes a single value as a parameter. You can't use this version in this case: when the mouse is
directly over the barrel, a division by zero will occur because adjacent is zero.
For situations where the arctangent needs to be calculated while taking into account possible
singularities such as this, there is an alternative arctangent method. The atan2 method takes opposite
and adjacent lengths as separate parameters and returns the equivalent in radians of 90 degrees in
this situation. You can use this method to calculate the angle, as follows:
Game.cannonRotation = Math.atan2(opposite, adjacent);
These instructions are all placed in update . Here is the complete method:
Game.update = function () {
var opposite = Game.mousePosition.y - Game.cannonPosition.y;
var adjacent = Game.mousePosition.x - Game.cannonPosition.x;
Game.cannonRotation = Math.atan2(opposite, adjacent);
};
The only thing left to do is to draw the sprites on the screen in the draw method, at the correct
position and at the correct angle:
Game.draw = function () {
Game.clearCanvas();
Game.drawImage(Game.backgroundSprite, { x : 0, y : 0 }, 0,
{ x : 0, y : 0 });
Game.drawImage(Game.cannonBarrelSprite, Game.cannonPosition,
Game.cannonRotation, Game.cannonOrigin);
};
What You Have Learned
In this chapter, you have learned:
How to read the current mouse position using an event handler, and how to
draw a sprite at the current mouse position
How to draw a sprite at an angle
How to change the angle at which a sprite is drawn based on the mouse position
 
Search WWH ::




Custom Search