Game Development Reference
Data from accelerometers can be used in games to change the screen
orientation, for example, turning a controller on its side, giving movement
commands such as bowling or batting in Wii Sports games, or moving a
character around in an environment, to name a few. The iPhone version
of Spore Origins , for example, allows players to navigate their creature
around in the primordial slime by tilting and rotating the device.
The accelerometer reports movement in 3D. In the case of Android, holding
the device in an upright portrait with the screen facing you, an x acceleration
will be registered if you tilt the phone forward and back, a y acceleration will
be registered as the phone is swiveled around its vertical midpoint, and z
acceleration is registered when the phone is brought toward and away
from you. This is illustrated in Figure 8.4 .
Fig 8.4 Acceleration axes of the
Google Nexus One HTC mobile.
To access a device's acceleration data from within Unity, the Input class
is used. When played on an iOS- or Android-enabled device (with an
accelerometer), Input.acceleration will return the device's acceleration
as a Vector3 value. The code in Listing 8.1 can be added to its own
device to display current acceleration values on the screen. The x , y , and
z values obtained in this example could be used to change transform
data of a game object and thus its position in the game world. Be careful
though! The X, Y, and Z of the device do not automatically match the X, Y,
and Z of your game world.