Book Image

Cocos2d-x by Example: Beginner's Guide

By : Roger Engelbert
Book Image

Cocos2d-x by Example: Beginner's Guide

By: Roger Engelbert

Overview of this book

Table of Contents (19 chapters)
Cocos2d-x by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – reading accelerometer data


Just as you do with touch events, you need to tell the framework you want to read accelerometer 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 accelerometer 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...