How to Add Tilt Controls to Your HTML5 Game

By Andy Harris

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.

  1. Create an Accel object.

    SimpleGame has an Accel object. Create this object to turn on accelerometer testing.

  2. Use methods to determine tilt.

    The Accel object has special methods called getAX() and getAY() that indicate the rotation amount.

  3. 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:

<html lang="en-US">
 <meta charset="UTF-8">
 <script type="text/javascript"
   src = "simpleGame.js"></script>
 <script type="text/javascript">
 var game;
 var ball;
 var accel
 function init(){
  game = new Scene();
  ball = new Sprite(game, "redBall.png", 50, 50);
  accel = new Accel();
 } // end init
 function update(){
  newDX = accel.getAY();
  newDY = accel.getAX();
  newDX *= -5;
  newDY *= -5;
<body onload = "init()">

The accelerometer is easy to use:

  1. Make a variable to hold the accelerometer object.

    You can call your variable accel.

  2. 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!

  3. 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.

  4. 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.

  5. 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.

  6. 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.