Game Development Reference
In-Depth Information
the ball based on the barrel orientation. Using the sine and cosine functions, you calculate the new
position as follows:
cannon.ballPosition = function() {
var opp = Math.sin(cannon.rotation) * sprites.cannon_barrel.width * 0.6;
var adj = Math.cos(cannon.rotation) * sprites.cannon_barrel.width * 0.6;
return { x : cannon.position.x + adj, y : cannon.position.y + opp };
};
As you can see, you multiply the opposite and adjacent sides with a value of 0.6 so the ball is drawn
a bit more than halfway up the rotated barrel. The method returns a new composite object that
has x and y variables containing the desired x and y positions of the ball.
After you've retrieved the desired ball position, you subtract half of the width and height of the ball
sprite from it. That way, the ball is drawn nicely in the middle of the cannon barrel.
The second part of the ball.update method also is an if instruction:
if (painterGameWorld.isOutsideWorld(ball.position))
ball.reset();
This part of the method deals with the event that occurs when the ball goes outside the game world.
In order to calculate if this is true, you add a method called isOutsideWorld to painterGameWorld . The
goal of this method is to check whether a given position is outside the game world. You define the
boundaries of the game world using a few simple rules. Remember that the top left of the screen is
the origin. An object is outside the game world if its x-position is smaller than zero or larger than the
width of the screen. An object is also outside the game world if its y-position is larger than the height
of the screen. Note that I don't say an object is outside the game world if its y-position is smaller than
zero. Why not? I chose to do this so it's possible for a player to shoot a ball in the air and let the ball
be momentarily above the screen before falling down again. Often you see a similar effect in platform
games, where a character can jump up and disappear partly outside the screen as opposed to falling
through the bottom of the screen (which generally means instant death of the character).
If you look at the header of this method, you see that it expects one parameter, a position:
painterGameWorld.isOutsideWorld = function (position)
If you want to check whether a position is outside the screen, you need to know the width and
height of the screen. In an HTML5 game such as Painter, this corresponds to the size of the canvas .
Painter4 adds a variable called size to Game . When the Game.start method is called, the desired size
of the screen is passed along as a parameter. Here is the extended Game.start method:
Game.start = function (canvasName, x, y) {
Canvas2D.initialize(canvasName);
Game.size = { x : x, y : y };
Keyboard.initialize();
Mouse.initialize();
Game.loadAssets();
Game.assetLoadingLoop();
};
 
Search WWH ::




Custom Search