Game Development Reference
In-Depth Information
var id = Touch.getTouchIndexFromId(touches[i].identifier);
Touch._touches.splice(id, 1);
Touch._touchPresses.splice(id, 1);
}
}
Finally, in handleTouchMove , you have to update the touch information for the touches that have
changed. This means you have to replace an element in the array. The splice method accepts a
third parameter in which you can indicate a replacement element. Have a look at the code belonging
to this chapter to see the implementation of the handleTouchMove event-handler function.
Making Dealing with Touch Input Easier
You've seen how touch input is handled in JavaScript. You can add a few more methods to the
Touch_Singleton class to make it easier to use in games. First is a simple method for retrieving the
position of a touch with a given index:
Touch_Singleton.prototype.getPosition = function (index) {
var canvasScale = Canvas2D.scale;
var canvasOffset = Canvas2D.offset;
var mx = (this._touches[index].pageX - canvasOffset.x) / canvasScale.x;
var my = (this._touches[index].pageY - canvasOffset.y) / canvasScale.y;
return new Vector2(mx, my);
};
Note that you have to apply the same position and scale correction as for the mouse position. The
pageX and pageY variables in the touch event provide the coordinates where the player is touching
the screen.
It would also be useful to check whether you're touching a certain area of the screen. For that, you
can add a class called Rectangle to the JewelJam1 example. This is a very simple class, similar to
Vector2 , for representing a rectangle. You can also add a few simple methods to check whether
two rectangles intersect (useful for collision checking) and whether a rectangle contains a certain
position. Check out the Rectangle.js file to see how to structure this class.
You can use rectangles to define portions of the screen. The containsTouch method checks whether
there is a touch in a rectangle provided as a parameter to the method:
Touch_Singleton.prototype.containsTouch = function (rect) {
for (var i = 0, l = this._touches.length; i < l; ++i) {
if (rect.contains(this.getPosition(i)))
return true;
}
return false;
};
 
Search WWH ::




Custom Search