Game Development Reference
In-Depth Information
Aiming the Barrel at the Mouse Pointer
In the previous sections, you've seen how to use the if instruction to check whether the player has
pressed the R key. Now, suppose you want to update the angle of the cannon barrel only if the left
mouse button is down. In order to handle mouse button presses, you need two more event handlers:
one for handling the event that the user presses a mouse button, and another for handling the event
that the user releases the mouse button. This is done in a way similar to pressing and releasing a key
on the keyboard. Whenever a mouse button is pressed or released, the which variable in the event
object tells you which button it was (1 is the left button, 2 is the middle button, 3 is the right button).
You can add a Boolean variable to the Mouse object that indicates whether a mouse button is down.
Let's do this for the left mouse button:
var Mouse = {
position : { x : 0, y : 0 },
leftDown : false
};
You also have to add the two handler functions that assign a value to the leftDown variable. Here are
the two functions:
function handleMouseDown(evt) {
if (evt.which === 1)
Mouse.leftDown = true;
}
function handleMouseUp(evt) {
if (evt.which === 1)
Mouse.leftDown = false;
}
As you can see, you use the if instruction to find out whether the left mouse button was pressed or
released. Depending on the truth value of the condition, you execute the body of the instruction. Of
course, you need to assign these handlers to the appropriate variables in the document so they're
called when a mouse button is pressed or released:
document.onmousedown = handleMouseDown;
document.onmouseup = handleMouseUp;
Now, in the update method of cannon , you update the cannon barrel angle only if the left mouse
button is down:
if (Mouse.leftDown) {
var opposite = Mouse.position.y - this.position.y;
var adjacent = Mouse.position.x - this.position.x;
cannon.rotation = Math.atan2(opposite, adjacent);
}
 
Search WWH ::




Custom Search