Game Development Reference
In-Depth Information
You can start and stop the updating of the heading and location information by using the
startUpdatingHeading
and
startUpdatingLocation
functions, and the
stopUpdatingHeading
and
stopUpdatingLocation
functions, respectively.
Accelerometer
The
Accelerometer
class is used to access the accelerometer data, if the device has an accelerometer.
To be able to access the accelerometer, you need to call
require "accelerometer"
, and when this
is loaded, a variable of type
Accelerometer
is created. It can be accessed as
accelerometer
. Then
you can call the
start
function on the
accelerometer
object. If at any time you need to stop the
accelerometer for any reason—including saving battery life or preventing unnecessary events from
being triggered—you can call the
stop
function.
require "accelerometer"
accelerometer:start()
function onEnterFrame(event)
local x, y, z = accelerometer:getAcceleration()
print(x, y, z)
end
stage:addEventListener("enterFrame", onEnterFrame)
Note
Running this code on the desktop player will just display a series of zeros, as the desktop player
does not have an accelerometer. To test this code, you should run it with the device player.
Gyroscope
All new iOS devices have gyroscopes that can be read from the device. First, we use the
require
"gyroscope"
command, which creates a variable called
gyroscope
that is of the
Gyroscope
class.
The data from the gyroscope is read using the
getRotationRate
function, which returns the rate of
rotation in radians.
require "gyroscope"
gyroscope:start()
local angx, angy, angz = 0,0,0
function onEnterFrame(event)
local x, y, z = gyroscope:getRotationRate()
angx = angx + x * event.deltaTime
angy = angy + y * event.deltaTime
angz = angz + z * event.deltaTime
print(angx * 180 / math.pi, angy * 180 / math.pi, angz * 180 / math.pi)
end
stage:addEventListener("enterFrame", onEnterFrame)