Adding Touch Controls

Since the introduction of the iPhone in 2007, the direction of input mobile devices has been clear: The touchscreen has won. To make Alien Invasion playable on mobile and table devices, it must be playable with only the screen as an input device.

Drawing Controls

To make mobile gameplay possible, the common solution is to add visible touch controls to the screen. These controls can consist of three square buttons at the bottom of the page: a left arrow to move the ship left, a right arrow to move the ship right, and an "A" button to fire.

To add in the controls, a new game board at a higher position than anything else is added in. Because it will be rendered after everything else, the controls always sit nicely on top of the page.

The game needs to handle different screen resolutions. To this end, instead of drawing fixed size input squares (which could end up being too large or too small depending on the device), the game adjusts the size of the squares based on the width of the game. Based on some informal testing, dividing the width of the game into five regions works well enough. Buttons are large enough to be hit easily but don't take up too much screen real estate.

The first step is to add the controls onto the page. Open up engine.js and add the following object (as shown in Listing 3-1) to the bottom.

Listing 3-1: TouchControls for Alien Invasion

var TouchControls = function() { var gutterWidth = 10; var unitWidth = Game.width/5; var blockWidth = ...

Get Professional HTML5 Mobile Game Development now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.