How to Calibrate the Accelerometer for Your HTML5 Game
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.
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:
Somehow you need to trigger the calibration. For this example, you add a basic calibration button. Here’s how it works:
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.
Add a calibrate button.
For this example, the user can recalibrate by clicking a button.
Check for a button press.
A function was created to read any button presses.
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.
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.