Game Development Reference
In-Depth Information
You can see in the body of this method that you use the
return
keyword to draw the ball only if it
isn't shooting. Inside the
painterGameWorld
object, you have to call the game-loop methods on
the ball. For example, this is the
draw
method in
painterGameWorld
, from which the
ball.draw
method is called:
painterGameWorld.draw = function () {
Canvas2D.drawImage(sprites.background, { x : 0, y : 0 }, 0,
{ x : 0, y : 0 });
ball.draw();
cannon.draw();
};
Note the order in which the game objects are drawn: first the background image, then the ball, and
then the cannon.
Shooting the Ball
The player can click the left mouse button in the game screen to shoot a ball of paint. The speed
of the ball and the direction in which it's moving are determined by the position where the player
clicks. The ball should move in the direction of that position; and the further from the cannon a
player clicks, the higher the speed of the ball. This is an intuitive way for the user to control the
speed of the ball. Whenever you design a game, think carefully about how instructions from the user
are received and what the most natural or efficient way is to process them.
In order to handle input, you add a
handleInput
method to the
ball
object. Inside this method, you
can check whether the player clicks with the left button by using the
Mouse
object:
if (Mouse.leftPressed)
// do something...
However, because there can be only a single ball in the air at any moment, you want to do
something only if the ball isn't already in the air. This means you have to check the ball's shooting
status. If the ball has already been shot, you don't have to handle the mouse click. So, you extend
your
if
instruction with an extra condition that the ball currently isn't in the air:
if (Mouse.leftPressed && !ball.shooting)
// do something...
As you can see, you're using two logical operators (
&&
and
!
) in conjunction. Because of the logical
not
(
!
) operator, the entire condition in the
if
instruction will evaluate to
true
only if the
shooting
variable has the value
false
: in other words, the ball is not currently shooting.
Inside the
if
instruction, you need to do a couple of things. You know the player has clicked
somewhere and that the ball has to be shot from the cannon. The first thing you need to do is set
the variable
shooting
to the correct value, because the status of the ball needs to be changed to
“currently shooting”:
ball.shooting = true;
Search WWH ::
Custom Search