Game Development Reference
In-Depth Information
In the draw method, you can now calculate the origin and pass it along to the drawImage method,
as follows:
Game.draw = function () {
Game.drawImage(Game.backgroundSprite, { x : 0, y : 0 }, { x : 0, y : 0 });
Game.balloonOrigin = { x : Game.balloonSprite.width / 2,
y : Game.balloonSprite.height };
Game.drawImage(Game.balloonSprite, Game.mousePosition, Game.balloonOrigin);
};
Using the Mouse Position to Rotate the Cannon Barrel
One of the features of the Painter game is that it contains a cannon barrel that rotates according to
the mouse position. This cannon is controlled by the player in order to shoot paint balls. You can
write the part of the program that does this, using the tools discussed in this chapter. You can see
this working in the Painter1 example belonging to this chapter.
You have to declare a few member variables to make this possible. First, you need variables for
storing the background and the cannon-barrel sprites. You also need to store the current mouse
position, just like you did in the previous examples in this chapter. Then, because you rotate the
cannon barrel, you need to store its position, its origin, and its current rotation. Finally, you need
the canvas and the canvas context so you can draw game objects. As usual, all these variables are
declared as members of the Game object:
var Game = {
canvas : undefined,
canvasContext : undefined,
backgroundSprite : undefined,
cannonBarrelSprite : undefined,
mousePosition : { x : 0, y : 0 },
cannonPosition : { x : 72, y : 405 },
cannonOrigin : { x : 34, y : 34 },
cannonRotation : 0
};
Both the position and the origin of the cannon barrel are given a value when the Game variable is
defined. The position of the barrel is chosen such that it fits nicely on the cannon base that is already
drawn on the background. The barrel image contains a circular part with the actual barrel attached to
it. You want the barrel to rotate around the center of the circular part. That means you have to set this
center as the origin. Because the circle part is at left on the sprite and the radius of this circle is half
the height of the cannon-barrel sprite (which is 68 pixels high), you set the barrel origin to (34, 34), as
you can see in the code.
To draw the cannon barrel at an angle, you need to apply a rotation when you draw the cannon-barrel
sprite on the screen. This means you have to extend the drawImage method such that it can take rotation
into account. Applying rotation is done through the rotate method that is part of the canvas context.
 
Search WWH ::




Custom Search