Game Development Reference
In-Depth Information
Here you also see an example of a nested if instruction, meaning the body of an if instruction contains
one or more if instructions itself. You can now write the code needed to toggle the cannon barrel's
behavior by writing an if instruction that checks whether the left mouse button has been pressed:
if (Mouse.leftPressed)
cannon.calculateAngle = !cannon.calculateAngle;
In the body of the if instruction, you toggle the calculateAngle variable. This is a Boolean member
variable of the cannon object. In order to get the toggling behavior, you use the logical not operator.
The result of the not operation on the variable calculateAngle is stored again in the variable
calculateAngle . So, if that variable contains the value true , you store in the same variable the value
false and vice versa. The result is that the value of the calculateAngle variable toggles every time
you execute that instruction.
You can now use that variable in another if instruction to determine whether you should update
the angle:
if (cannon.calculateAngle) {
var opposite = Mouse.position.y - this.position.y;
var adjacent = Mouse.position.x - this.position.x;
cannon.rotation = Math.atan2(opposite, adjacent);
} else
cannon.rotation = 0;
In order to finalize this example, you need to do a bit of extra bookkeeping. Currently, the
variable Mouse.leftPressed is never reset. So, after each execution of the game loop, you reset
Mouse.leftPressed to false . You add a reset method to the Mouse object that does this, as follows:
Mouse.reset = function() {
Mouse.leftPressed = false;
};
And finally, this method is called from the mainLoop method in the Game object:
Game.mainLoop = function() {
Game.update();
Game.draw();
Mouse.reset();
window.setTimeout(Game.mainLoop, 1000 / 60);
};
What You Have Learned
In this chapter, you have learned:
if instructions
How to formulate conditions for these instructions using Boolean values
How to react to mouse clicks and button presses using
if instructions with different alternatives
How to use
 
Search WWH ::




Custom Search