Game Development Reference
alpha = alpha * (180/PI);
alpha = alpha * (-180/PI) + 180;
This is pretty straightforward, but there are a few things to point out. First, the way in
which your program will get results from the accelerometer will vary greatly between
platforms, so we have encapsulated that API-specific code in a getXacceleration()
function. In fact, most operating systems will be continuously polling the accelerometer
in a separate thread, so you'll have to have a logical operator that tells your accelerometer
object when you actually want to see those values passed to your program. Example
Objective-C code for the accelerometer in the iPhone will be shown later. Secondly,
you'll notice that we are using an if statement that changes the radians to degrees in
such a way as to return proper 0°-360° answers. This avoids having to pay attention to
the sign, as atan2 returns only answers between 0° and 180°, using a negative value to
represent the other half of the range. For example, an output of 0° means the device is
vertical, an output of 90° means the device is rotated 90° to the left, and an output of
180° means the device is upside down.
Now let's extend this to two dimensions. This will tell us not only how far the phone is
from vertical about one axis, but its inclination about the y-axis as well.
Two Degrees of Freedom
Now let's say that we want to develop a game in which we control a sprite moving in a
2D world. The user would hold the device as if it were lying on a table and look down
from above. He or she would then tilt the phone out of that plane to get the sprite to
move in the desired direction. The fraction of gravity that the accelerometer is now
experiencing in the x- and y-directions will be inputs into our simulation.
The example will be demonstrated using Objective-C code for the iPhone, and we'll be
using the Qwartz2D graphics framework. If you aren't familiar with Objective-C, don't
worry—we'll explain what we are doing in each step, and you can port that code to
whatever language you are working in.
The first step will be to set up our accelerometer. In this case we are going to initialize
it in our tiltViewController.m file so that we have:
UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
accelerometer.delegate = self;
accelerometer.updateInterval = kPollingRate;