Changing gravity by using the acceleration sensor
A game with a physics engine will often change the direction of gravity by tilting the device. By doing so, it is possible to add realism in the game. In this recipe, you can change the direction of gravity by using an acceleration sensor.
Getting ready
To avoid screen rotation, you have to change some code and settings. Firstly, you should set Device Orientation to only Landscape Right as shown in the following image:
Secondly, you change the shouldAutorotate
method's return value to false in RootViewController.mm
.
- (BOOL) shouldAutorotate { return NO; }
How to do it...
You check the acceleration sensor value in HelloWorld.cpp
as follows:
Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create([=](Acceleration* acc, Event* event){ auto gravity = Vec2(acc->x*100.0f, acc->y*100.0f); world->setGravity(gravity); }); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener...