HTML and CSS Reference
In-Depth Information
Responding to Touch Events
To make these boxes work with touch events, the game needs to be set up to listen for a new set of browser
events: touchstart , touchmove , and touchend . You've most likely come across browser events before,
such as the well-known click event. These new events are available on non-Windows touch devices only and
are special in that they contain not only the details about the event, but also about any other touches currently on
the device. The details for these additional events are held in three arrays inside of the event object, described
in Table 3-1 .
Table 3-1: Touch Event Properties
Event Property
Description
All the touches currently on the devices
event.touches
event.targetTouches All the touches on the same DOM object as the event
event.changedTouches All the touches changed in this event
The game uses both the targetTouches array and the changedTouches array to good effect.
The targetTouches is used for the two buttons on the left that control movement. You want the user to
be able to press and hold down either button to move left and right. As such, each time there is a touch event,
the game sees if there are any touches currently hitting either of those two buttons and marks the button as down
if that is the case, even if the touch that triggered the event isn't on either button.
For firing, as a design choice, the game requires the player to press the Fire button each time they want to
fire a missile. (Holding down the fire key doesn't count.) For that reason, the game counts the fire key as down
only if the user actually pressed that key in the last step.
Add the code in Listing 3-2 to the TouchControls class before the ending curly brace:
Listing 3-2: TouchControls touch tracking
var TouchControls = function() {
...
this.step = function(dt) { };
this.trackTouch = function(e) {
var touch, x;
e.preventDefault();
Game.keys['left'] = false;
Game.keys['right'] = false;
for(var i=0;i<e.targetTouches.length;i++) {
touch = e.targetTouches[i];
x = touch.pageX / Game.canvasMultiplier - Game.canvas.offsetLeft;
if(x < unitWidth) {
Game.keys['left'] = true;
}
if(x > unitWidth && x < 2*unitWidth) {
Game.keys['right'] = true;
}
}
 
 
 
 
Search WWH ::




Custom Search