Game Development Reference
In-Depth Information
Time for action - reading accelerometer
data
Just as you do with
touch
events, you need to tell the framework you want to read accel-
erometer data.
1. You tell the framework you wish to use the accelerometer with this one call inside
any
Layer
class:
Device::setAccelerometerEnabled(true);
2. Then, just as you've done with
touch
events, you subscribe to the
accelero-
meter
events from the event dispatcher as follows:
auto listenerAccelerometer =
EventListenerAcceleration::create(CC_CALLBACK_2
(GameLayer::onAcceleration, this));
_eventDispatcher->addEventListenerWithSceneGraphPriority(listenerAccelerometer,
this);
3. In Eskimo, the accelerometer data changes the value of a
Point
vector called
_acceleration
.
void GameLayer::onAcceleration(Acceleration *acc,
Event *event) {
_acceleration = Vec2(acc->x *
ACCELEROMETER_MULTIPLIER,
acc->y *
ACCELEROMETER_MULTIPLIER);
}
This value is then read inside the main loop and used to move the Eskimo. In the
game, only one axis is updated at a time, depending on the current gravity. So you
can only ever move the Eskimo on the
X
axis or the
Y
axis with the accelerometer
data, but never both at the same time.