How to Calibrate the Accelerometer for Your HTML5 Game

By Andy Harris

By default, the HTML5 game accelerometer assumes the neutral position of perfectly horizontal — that is, the device is lying flat on a table. However, these are mobile devices, and gamers will often want to have the neutral position be somewhere else.

image0.jpg

The basic technique for calibrating tilt controls is to keep track of an offset value for AX and AY. When the user chooses to recalibrate, the offset values are changed to make a new neutral position. Here’s the relevant code:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
 <meta charset="UTF-8">
 <title>accel.html</title>
 <script type="text/javascript"
   src = "simpleGame.js"></script>
 <script type="text/javascript">
 var game;
 var ball;
 var accel;
 var btnCalibrate;
 var offsetAX = 0;
 var offsetAY = 0;
 function init(){
  game = new Scene();
  ball = new Sprite(game, "redBall.png", 50, 50);
  accel = new Accel();
  btnCalibrate = new GameButton("calibrate");
  btnCalibrate.setSize(100, 100);
  btnCalibrate.setPosition(100, 100);
  game.start();
 } // end init
 function checkButton(){
  if (btnCalibrate.isClicked()){
   offsetAY = accel.getAY();
   offsetAX = accel.getAX();
  }
 }
 function update(){
  game.clear();
  checkButton();
  newDX = accel.getAY() - offsetAY;
  newDY = accel.getAX() - offsetAX;
  newDX *= -5;
  newDY *= -5;
  ball.setDX(newDX);
  ball.setDY(newDY);
  ball.update();
 }
 </script>
</head>
<body onload = "init()">
</body>
</html>

Somehow you need to trigger the calibration. For this example, you add a basic calibration button. Here’s how it works:

  1. Add offsetAX and offsetAY variables.

    These two variables indicate how much the device’s neutral position is different than the standard flat-on-the-table attitude. Begin the variables at value zero.

  2. Add a calibrate button.

    For this example, the user can recalibrate by clicking a button.

  3. Check for a button press.

    A function was created to read any button presses.

  4. If the button is pressed, get new offset values.

    When the button is active, find the current AX and AY values by requesting them from the Accel object.

  5. Subtract offsets from ax and ay on every frame.

    Before any other calculations, subtract the offsetAX from AX and offsetAY from AY. This will effectively set the new neutral position to however the device was set the last time the button was clicked.

Although a calibrate button is very easy to implement, sometimes the calibration is done automatically. If you prefer, just determine offsetAX and offsetAY during the init() function, and the attitude of the device during the init() function becomes the default attitude. This doesn’t allow the user to reset the calibration, but it does prevent cluttering the screen with a rarely used button.