Game Development Reference
In-Depth Information
As you can see, you have two position variables: one for the cannon barrel and one for the colored
sphere. Furthermore, you add a variable that refers to the current color of the sphere that should be
drawn. Initially, you assign the red sphere sprite to this variable.
In order to make a clear separation between the objects, you can also add a draw method to the
cannon object. In this method, you draw the cannon barrel and the colored sphere on top of it:
cannon.draw = function () {
Canvas2D.drawImage(sprites.cannon_barrel, cannon.position, cannon.rotation,
cannon.origin);
Canvas2D.drawImage(cannon.currentColor, cannon.colorPosition, 0,
{ x : 0, y : 0 });
};
This draw method is called from Game.draw as follows:
Game.draw = function () {
Canvas2D.clear();
Canvas2D.drawImage(sprites.background, { x : 0, y : 0 }, 0,
{ x : 0, y : 0 });
cannon.draw();
};
That way, you can more easily see which drawing instructions belong to what object. Now that the
preparatory work has been done, you can start handling the player's keypresses. Until now, all the
instructions you've written had to be executed all the time. For example, the program always needs
to draw the background sprite and the cannon barrel sprite. But now you encounter a situation
where you need to execute instructions only if some condition is met. For example, you need to
change the color of the ball to green only if the player presses the G key . This kind of instruction is
called a conditional instruction , and it uses a new keyword: if .
With the if instruction, you can provide a condition and execute a block of instructions if this condition
holds (in total, this is sometimes also referred to as a branch ). Here are some examples of conditions:
The player has pressed the G key.
The number of seconds that have passed since the start of the
game is larger than 1,000.
The balloon sprite is exactly in the middle of the screen.
The monster has eaten your character.
These conditions can either be true or false . A condition is an expression , because it has a value
(it's either true or false ). This value is also called a Boolean value. With an if instruction, you can
execute a block of instructions if a condition is true. Take a look at this example if instruction:
if (Game.mousePosition.x > 200) {
Canvas2D.drawImage(sprites.background, { x : 0, y : 0 }, 0,
{ x : 0, y : 0 });
}
 
Search WWH ::




Custom Search