Game Development Reference
In-Depth Information
In the event-handler functions, you're changing the values of the member variables. In the
handleMouseMove event-handler function, you have to calculate the mouse position. This is also the
place where you make sure the mouse position is scaled and moved according to the scale and
offset applied to the canvas. Here is the complete handleMouseMove function:
function handleMouseMove(evt) {
var canvasScale = Canvas2D.scale;
var canvasOffset = Canvas2D.offset;
var mx = (evt.pageX - canvasOffset.x) / canvasScale.x;
var my = (evt.pageY - canvasOffset.y) / canvasScale.y;
Mouse._position = new Vector2(mx, my);
}
Now, whenever the mouse is moved, the mouse position is calculated correctly. The next thing
you need to do is handle mouse-button down and up events. A mouse button is pressed only if
the button is currently down when it wasn't in the previous game loop iteration. For the left mouse
button, here is how you express this:
if (evt.which === 1) {
if (!Mouse._left.down)
Mouse._left.pressed = true;
Mouse._left.down = true;
}
The evt.which value indicates whether you're dealing with the left (1), middle (2), or right (3) mouse
button. Have a look at the JewelJam1 example for the complete handleMouseDown event-handler
function. In the handleMouseUp event handler, you set the down variable to false again. Here is the
complete function:
function handleMouseUp(evt) {
handleMouseMove(evt);
if (evt.which === 1)
Mouse._left.down = false;
else if (evt.which === 2)
Mouse._middle.down = false;
else if (evt.which === 3)
Mouse._right.down = false;
}
You can see that you call the handleMouseMove function here as well. This is done to make sure
the mouse position is available when you press a mouse button. If you omit this line, and the
player starts the game and presses a mouse button without having moved the mouse, the game
will try to handle a mouse-button press without having position information. This is why you call
the handleMouseMove function in both the handleMouseDown and handleMouseUp functions (although
probably the latter isn't required).
 
Search WWH ::




Custom Search