Game Development Reference
In-Depth Information
change the color of the cannon if the mouse is in the left part of the screen. You can achieve that
as follows:
cannon.handleInput = function () {
if (Mouse.position.x > 10)
return;
if (Keyboard.keyDown === Keys.R)
cannon.currentColor = sprites.cannon_red;
else if (Keyboard.keyDown === Keys.G)
// etc.
};
In this method, you first check if the mouse x-position is greater than 10. If that is the case, you
execute the return instruction. Any instructions after that will then no longer be executed.
Notice that whenever a method with no return value is called, it has no result that can be stored in a
variable. For example:
var what = cannon.handleInput();
Because cannon.handleInput doesn't have a return value, the variable what will have the value
undefined after this instruction is executed.
If a method or function has a return value, this value doesn't necessarily have to be stored in a
variable. You can also directly use it in an if instruction, as you do in the cannon.handleInput method:
if (Math.random() > 0.5)
// do something
Here, the Math.random method returns a number and if that number is greater than 0.5, the body of
the if instruction is executed. The difference between things that have a value and things that don't
have a value is something you've seen before: it's the same difference you saw between instructions
(which don't have a value) and expressions (which do have a value). So, this means Math.random()
is an expression , whereas cannon.handleInput(); is an instruction . A second difference between
these two things is that expressions never end with a semicolon, and instructions always end with a
semicolon, unless the instruction is a block.
DECLARATIONS VS. PARAMETERS
Declarations of variables have a lot in common with parameters that are written in the method header. In fact, those
parameters also are declarations, but there are a few differences:
Variables are declared in the body of the method; parameters are declared between the parentheses
in the method header.
Variables get a value by using an assignment instruction; parameters automatically get a value
when the method is called.
var ; parameter declarations don't.
Variable declarations end with a semicolon; parameter declarations don't.
Variable declarations start with the word
 
Search WWH ::




Custom Search