How to Add Tilt Controls to Your HTML5 Game
Mobile devices have a very intriguing input mechanism that allows you to control objects in an HTML5 game by tilting. This works with a special on-board tool called the accelerometer, which tracks motion. The accelerometer actually measures rotation, and you can use it to get nice tilt controls in your game.
The simpleGame library has a special object called Accel that encapsulates the accelerometer. It works very much like the Joy object.
Create an Accel object.
SimpleGame has an Accel object. Create this object to turn on accelerometer testing.
Use methods to determine tilt.
The Accel object has special methods called getAX() and getAY() that indicate the rotation amount.
Modify acceleration values.
The AX and AY values display the amount of rotation around the X and Y axis, respectively. The values range from –9 to 9. Generally, you’ll need to modify the tilt values to get exactly the behavior you want. This usually involves a few simple math calculations.
Here’s the code for accel.html:
The accelerometer is easy to use:
Make a variable to hold the accelerometer object.
You can call your variable accel.
Use accel.getAX() to get rotation around X.
The getAX() method returns the percentage of tilt around the X axis. The X axis goes from side to side on the screen, so rotation around X is normally tied to motion along the Y axis!
Use acccel.getAY() to determine rotation around Y.
Likewise, the getAY() method describes the percentage of tilt along the (vertical) Y axis. Normally, you’ll use getAY() to control horizontal motion.
Don’t be concerned about the Z axis.
You can also read rotation along the Z axis (which goes from the center of the screen to your nose), but this is generally not helpful.
Assume (for now) that the neutral position is lying perfectly flat on a table.
You’ll get zero values for getAX() and getAY() when the device is lying completely still on a perfectly flat table.
Experiment with scaling factors.
You’ll generally have to multiply the getAX() and getAY() results by some amount to get the behavior you want. If you multiply both by negative five, you will get appropriate values for dy and dx. You’ll need to experiment to get exactly the behavior you want.