Game Development Reference
In-Depth Information
Here you can see a nice way of making the sprite-loading calls more readable in JavaScript. You
declare a local variable
loadSprite
that refers to a function. This function takes as a parameter a
sprite image name and calls the
Game.loadSprite
method. As a parameter to that method, you pass
along the folder path of the sprite plus the name of the sprite. Finally, the function returns the result
of the
Game.loadSprite
method.
Creating the Ball
Let's get back to the
ball
object. In the
initialize
method of that object, you have to assign values
to the member variables, just as in the case of the
cannon
object. When the game starts, the ball
should not be moving. Therefore, you set the velocity of the ball to zero. Also, you initially set the
ball to the zero position. That way, it's hidden behind the cannon, so when the ball isn't moving, you
don't see it. You initially set the color of the ball to red, and you set the
shooting
member variable to
false
. Here is the complete method:
ball.initialize = function() {
ball.position = { x : 0, y : 0 };
ball.velocity = { x : 0, y : 0 };
ball.origin = { x : 0, y : 0 };
ball.currentColor = sprites.ball_red;
ball.shooting = false;
};
Next to the
initialize
method, you also add a
reset
method that resets the ball position and its
shooting status:
ball.reset = function () {
ball.position = { x : 0, y : 0 };
ball.shooting = false;
};
When the ball flies outside of the screen after it has been shot from the cannon, you can reset it
by calling this method. Furthermore, you add a
draw
method to the
ball
object. If the ball isn't
shooting, you don't want the player to see it. So, you draw the ball sprite only if the ball is
currently shooting:
ball.draw = function () {
if (!ball.shooting)
return;
Canvas2D.drawImage(ball.currentColor, ball.position, ball.rotation,
ball.origin);
};
Search WWH ::
Custom Search