Game Development Reference
In-Depth Information
In the
isOutsideWorld
method, you use the
Game.size
variable to determine whether a position is
outside the game world. The body of the method consists of a single instruction using the keyword
return
to calculate a Boolean value. The logical
or
operation is used to cover the different cases in
which the position is outside the game world:
return position.x < 0 || position.x > Game.size.x || position.y > Game.size.y;
As you can see, you don't mind if the y coordinate is smaller than zero. This allows you to have the
ball end up above the screen and fall back in again.
Let's return to the
ball.update
method. The second
if
instruction calls the
isOutsideWorld
method
in its condition; and if this method returns the value
true
, then the
ball.reset
method is executed.
Or, in simpler terms: if the ball flies out of the screen, it's placed at the cannon, ready to be shot
again by the player. Here you see another advantage of grouping instructions in methods: methods
such as
isOutsideWorld
can be
reused
in different parts of the program, which saves development
time and results in shorter, more readable programs. For example,
isOutsideWorld
will probably also
be useful for the paint cans later in the game, to test whether they have fallen out of the screen.
Finally, you make sure to call the
ball.update
method in the
painterGameWorld.update
method:
painterGameWorld.update = function (delta) {
ball.update(delta);
cannon.update(delta);
};
When you run the Painter4 example, you can see that it's now possible to aim the cannon, choose a
color, and shoot a ball. In the next chapter, you add paint cans to this game. But in order to do that,
I have to introduce a new JavaScript programming concept:
prototypes
.
What You Have Learned
In this chapter, you have learned:
How to separate code over different source files
How to make the game loop more efficient
The different kinds of methods/functions (with/without parameters,
and with/without a return value)
The difference between fixed and variable timestep
How to add a flying ball to the game world
Search WWH ::
Custom Search