Game Development Reference
In-Depth Information
from true vertical. We are considering these the “gross” orientations such that these
small deviations should be ignored.
Sensing Tilt
Although we can't determine exactly what angle the user is holding the phone about all
three axes, we can pick one axis, assume that it is pointing down, and then find the
change in the angle from that assumption over time. For instance, if the phone is lying
on a table, the average acceleration in the z-direction will be −1, and in the other di‐
rections, 0. Even if the user spins the phone, the values will remain as previously indi‐
cated and we cannot sense that rotation. However, if the user lifts one edge from the
table—we'll call this tilting it—then the accelerometer will register different values.
Some of the acceleration due to gravity will act on the other two axes. By sensing this
change, an accelerometer will allow us to determine at what angle the device is tilted.
Using Tilt to Control a Sprite
Here we will show you how to implement code for a simple game that asks the user to
move an avatar to a target by tilting the phone. First, we will briefly show an example
of determining the rotation about a single axis. Let's assume we have an accelerometer
rotated at some arbitrary angle, α, which is what our algorithm will solve for. As previ‐
ously discussed, accelerometers generally report values as multiples of near earth gravity,
g . For the following example, we are concerned only with the x- and y-axis values, a x
and a y , respectively. If the device were in the “upright” position, then a x would equal 0
and a y would equal 1. After rotating the device, we'd see different values that are related
to our angle α by use of the arctangent function. In this case, because the single-argument
atan function included in most programming languages doesn't differentiate between
diametrically opposed directions, it is beneficial to use the two-argument function . The
relevant C code is as follows:
#define PI 3.14159
float find2dAngle(void){
//LOCAL VARIABLES
float alpha,
double ax, ay;
//POLL ACCELEROMETER FOR ACCELERATIONS, API SPECIFIC
ax = getXacceleration();
ay = getYacceleration();
//FIND ANGLE
alpha = atan2(ay,ax);
if (alpha >= 0){