Game Development Reference
In-Depth Information
variable
changedTouches
. For each element in that array, you add the touch event data to
the
_touches
array. Because these are new touches, you also add
true
values to the
_touchPresses
variable. This is the complete method:
function handleTouchStart(evt) {
evt.preventDefault();
var touches = evt.changedTouches;
for (var i = 0; i < touches.length; i++) {
Touch._touches.push(touches[i]);
Touch._touchPresses.push(true);
}
}
Note that the first instruction in this function is
evt.preventDefault();
. This method call makes sure
the touch event isn't used for default behavior (such as scrolling). You also place that instruction in
the other touch event-handler functions. In
handleTouchEnd
, you need to remove the touch from both
the arrays in your class. For that, you have to search through the array to find the data belonging to
the particular touch ID. To make this a bit easier, you add a method
getTouchIndexFromId
to your
class that finds the index in the array for you. Later, you can call this method to find where the touch
is stored in the array, and then remove that element.
In the method, you walk through all the elements in the array using a
for
loop. When you find the
touch that matches the identifier of the touch data you're looking for, you return that data. If the
touch data can't be found, you return the value -1. Here is the complete method:
Touch_Singleton.prototype.getTouchIndexFromId = function (id) {
for (var i = 0, l = this._touches.length; i < l; ++i) {
if (this._touches[i].identifier === id)
return i;
}
return -1;
};
In the
handleTouchEnd
function, you walk through the
changedTouches
variable with a
for
loop. For
each touch, you find the corresponding index and remove the touch from the two arrays (
_touches
and
_touchPresses
). Removing an element from an array is done with the
splice
method. This
method takes an index and a number: the index indicates where the element should be removed,
and the second parameter indicates how many elements should be removed. Here is an example:
var myArray = [2, 56, 12, 4];
myArray.splice(0,1); // myArray now contains [56, 12, 4]
myArray.splice(1,2); // myArray now contains [56]
Here is the full
handleTouchEnd
function:
function handleTouchEnd(evt) {
evt.preventDefault();
var touches = evt.changedTouches;
for (var i = 0; i < touches.length; ++i) {
Search WWH ::
Custom Search