Game Development Reference
In-Depth Information
Game.gameWorld.draw();
Mouse.reset();
requestAnimationFrame(Game.mainLoop);
};
As a result, you have nicely separated the generic game code (in Game.js ) and the game-specific
code, which consists of loading the sprites and initializing the game ( Painter.js ) and updating and
drawing the Painter game objects ( PainterGameWorld.js ). Any other game objects specific to Painter
are each defined in their own script file (such as Cannon.js ).
Adding a Ball to the Game World
In the previous sections, you saw how to make your JavaScript game applications more flexible
and efficient by being able to load separate JavaScript files, by separating generic game code from
Painter-specific code, by loading assets properly, and by creating a more efficient game loop. In this
section, you extend the Painter game by adding a ball that is shot by the cannon object. For that,
you add a ball object.
You set up the ball object in a fashion very similar to the cannon object. In the Painter4 example, you
see a version of the Painter game that adds a ball to the game world (see Figure 7-1 ). The ball can
be shot from the cannon by clicking anywhere in the game screen. Furthermore, the ball changes
color together with the cannon. You can find the code that describes the ball object in the Ball.js file.
Just like the cannon object, ball consists of a number of variables, such as a position, the current
color of the ball, and the origin of the ball sprite. Because the ball moves, you also need to store
its velocity . This velocity is a vector that defines how the position of the ball changes over time. For
example, if the ball has a velocity of (0,1), then every second, the y-position of the ball increases by
1 pixel (meaning the ball falls down). Finally, the ball can be in two states: it's either flying through the
air because it was shot from the cannon, or it's waiting to be shot (so it isn't moving). For that, you
add to the ball object an extra Boolean variable called shooting . This is the complete definition of
the structure of the ball object:
var ball = {
};
ball.initialize = function() {
ball.position = { x : 65, y : 390 };
ball.velocity = { x : 0, y : 0 };
ball.origin = { x : 0, y : 0 };
ball.currentColor = sprites.ball_red;
ball.shooting = false;
};
 
Search WWH ::




Custom Search