c++cocos2d-xaccelerometercocos2d-android

How to use Accelerometer in cocos2dx


I've been trying to get the acceleromter to work in cocos2d-x c++. I tried to add this function to my scene which a lot of my Google search results said I should:

virtual void didAccelerate(Acceleration *acceleration);

That does however give me an error saying I'm overriding a final function. Then I found how I could use the EventDispatcher thing for it.

    auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(MainScene::accelerated, this));
getEventDispatcher()->addEventListenerWithSceneGraphPriority(accListener, this);

In both of these I had called this function earlier in my scene's init function:

    setAccelerometerEnabled(true);

I'm all out of ideas and I need help. On the second "approach" it compiled, but my accelerated function was never called.

Thank you in advance!

I'm using Android so maybe I need to edit something in the AndroidManifest?


Solution

  • The guys at the cocos forums linked me to this: Cocos docs

    As you can see the correct way to go is to use the EventListener approach as described earlier. However you need to call

    Device::setAccelerometerEnabled(true);
    

    Calling

    setAccelerometerEnabled(true);
    

    From the scene's init doesn't work, you need to call the static method on 'Device'.

    So here's how you do it.

    Device::setAccelerometerEnabled(true);
    auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(MainScene::accelerated, this));
    getEventDispatcher()->addEventListenerWithSceneGraphPriority(accListener, this);
    

    Where accelerated is takes these parameters:

    void accelerated(Acceleration *acceleration, Event *event);
    

    Of course this function can be called anything as the EventListener takes a function pointer.