Game Development Reference
In-Depth Information
In the method body is a for loop that checks, for each touch in the array, whether its position falls
inside the rectangle. You reuse the getPosition method defined earlier. Depending on the outcome,
the method returns either true or false . Also add the following property to Touch :
Object.defineProperty(Touch_Singleton.prototype, "isTouchDevice",
{
get: function () {
return ('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0);
}
});
This is a very simple property for checking whether you're currently dealing with a touch device.
Not all browsers detect this the same way, so that is a good reason to encapsulate it in a method or
property. That way, you only have to deal with these differences between browsers once. Afterward,
you access the Touch.isTouchDevice property, and you're done.
Adding Touch Input to Painter
It would be a pity not to add touch to the Painter game now that you have this nice Touch object.
The example code belonging to this chapter has a version of Painter with touch input. Look at the
example code, in particular the Cannon.js file, where touch input has been added. In the touch
interface, you can tap the colored ball in the cannon barrel to switch to a different color. Tapping
outside the cannon aims the cannon. Releasing the touch afterward shoots the ball.
To separate touch-input handling from mouse-input handling, you can rewrite the handleInput
method as follows:
Cannon.prototype.handleInput = function (delta) {
if (Touch.isTouchDevice)
this.handleInputTouch(delta);
else
this.handleInputMouse(delta);
};
Now you write two separate methods for handling touch and mouse input. This is what the
handleInputTouch method looks like:
Cannon.prototype.handleInputTouch = function (delta) {
var rect = this.colorSelectRectangle;
if (Touch.containsTouchPress(rect)) {
if (this.currentColor === this.colorRed)
this.currentColor = this.colorGreen;
else if (this.currentColor === this.colorGreen)
this.currentColor = this.colorBlue;
else
this.currentColor = this.colorRed;
 
Search WWH ::




Custom Search