Game Development Reference
In-Depth Information
Redesigning Mouse-Input Handling
After doing all this, you've moved around the div and canvas elements quite a bit. In the Painter
game, you assumed that the canvas was always drawn at top left on the screen. Here, this is no
longer the case. If you want to detect mouse clicks on the screen, you need to take the position of
the canvas on the screen into account when calculating the local position of the mouse on the
game screen. Furthermore, because you applied a scale, you also need to scale the mouse
position accordingly.
This is a good opportunity to have another look at the way the input-handling classes Mouse and
Keyboard are designed. One thing you never properly implemented was dealing with keyboard or
mouse-button up and down versus keyboard or mouse button presses . Furthermore, in the Mouse
class, you only considered left button presses; and in the Keyboard class, only a single key could
be pressed at the same time. You can use the power of object-oriented programming through
JavaScript's prototype system to design a better solution.
The first step is creating a simple class that can store the state of a button (regardless of whether
it's a key or a mouse button). Let's call this class ButtonState . The ButtonState class is very simple
and only has two ( boolean ) member variables: one to indicate if the button is down, and another to
indicate if the button is pressed. Here is the complete class:
function ButtonState() {
this.down = false;
this.pressed = false;
}
Now you use ButtonState instances in the Mouse class to represent the states of the left, middle, and
right mouse buttons. This is what the new constructor of Mouse looks like:
function Mouse_Singleton() {
this._position = Vector2.zero;
this._left = new ButtonState();
this._middle = new ButtonState();
this._right = new ButtonState();
document.onmousemove = handleMouseMove;
document.onmousedown = handleMouseDown;
document.onmouseup = handleMouseUp;
}
As you can see, you have member variables for the buttons next to the member variables associated
with each position. You add read-only properties to access these variables. For example, if you want
to check whether the middle mouse button is down, you can do that with the following simple line
of code:
if (Mouse.middle.down)
// do something
 
Search WWH ::




Custom Search