Game Development Reference
In-Depth Information
There is a similar notation for other basic arithmetic operations, for example:
i -= 12; // this is the same as i = i - 12
i *= 0.99; // this is the same as i = i * 0.99
i /=5; // this is the same as i = i / 5
i--; // this is the same as i = i - 1
This notation is very useful, because it allows you to write shorter code. For example, the
following code:
Game.gameWorld.lives = Game.gameWorld.lives - penalty;
...becomes:
Game.gameWorld.lives -= penalty;
When you look at the example code belonging to this chapter, you will see that this shorter notation
is used in many different classes to make the code more compact.
A More Compact Looping Syntax
Many while instructions use a counting variable and therefore have the following structure:
var i;
i = begin value ;
while (i < end value ) {
// do something useful using i
i++;
}
Because this kind of instruction is quite common, a more compact notation is available for it:
var i;
for (i = begin value ; i < end value ; i++ ) {
// do something useful using i
}
The meaning of this instruction is exactly the same as the earlier while instruction. The advantage of
using the for instruction in this case is that everything that has something to do with the counter is
nicely grouped together in the header of the instruction. This reduces the chance of you forgetting
the instruction to increment the counter (resulting in an endless loop). In the cases where “do
something useful using i ” consists of only a single instruction, you can leave out the braces, which
makes the notation even more compact. Also, you can move the declaration of the variable i in the
header of the for instruction. For example, look at the following code fragment:
for (var i = 0; i < this.lives; i++) {
Canvas2D.drawImage(sprites.lives,
new Vector2(i * sprites.lives.width + 15, 60));
}
 
Search WWH ::




Custom Search