Game Development Reference
In-Depth Information
Chapter 6
Reacting to Player Input
In this chapter, you see how your game program can react to button presses. In order to do this,
you need an instruction called if that executes an instruction (or a group of instructions) when a
condition is met. You also learn to structure your code a bit more into objects and methods.
Objects in Games
Until now, all the example programs have had one big object called Game . This object consists of a
number of variables for storing the canvas and its context, sprites, positions, and so on. This is what
the Game object from the Painter1 example looks like:
var Game = {
canvas : undefined,
canvasContext : undefined,
backgroundSprite : undefined,
cannonBarrelSprite : undefined,
mousePosition : { x : 0, y : 0 },
cannonPosition : { x : 72, y : 405 },
cannonOrigin : { x : 34, y : 34 },
cannonRotation : 0
};
As you can see, it already contains quite a few variables, even for a simple program that only draws
a background and a rotating cannon. As the games you develop become more complicated, this
list of variables will grow, and as a result, the code will become harder for other developers to
understand (and for you, when you don't look at the code for a few months). The problem is that you
store everything in a single, big object called Game . Conceptually, this makes sense, because Game
contains everything pertaining to the Painter game. However, the code will be easier to understand if
you separate things a little.
If you look at the contents of the Game object, you can see that certain variables belong together
in some way. For example, the canvas and canvasContext variables belong together because they
both concern the canvas. Also, quite a few variables store information about the cannon, such as its
67
 
Search WWH ::




Custom Search