Search code examples
iosiphonexcodecocos2d-xaccelerometer

Cocos2d-x Accelerometer x y interchanged in iPhone6 and iPhoneX


Works perfect in iPhoneX. In iPhone6 when I tilt in landscape mode then accelerometer value comes even in Portrait game. How to get accelerometer value in portrait tilt ? Game is in Portrait. But accelerometer treat it as landscape..

Here is Code:

    Device::setAccelerometerEnabled(true);

    mAccelerometerListener = EventListenerAcceleration::create(CC_CALLBACK_2( GBGameScene::onAcceleration, this));
    _eventDispatcher->addEventListenerWithSceneGraphPriority(mAccelerometerListener, this);

Accelerometer Code:

void GBGameScene::onAcceleration(Acceleration* acc, Event* event)
{
    //  Processing logic here

    float deceleration = 1.0f;
    float maxVelocity = 100;

    playerVelocity.x = playerVelocity.x * deceleration + acc->x;
    playerVelocity.y = playerVelocity.y * deceleration + acc->y;

    if (playerVelocity.x > maxVelocity)
    {
        playerVelocity.x = maxVelocity;
    }
    else if (playerVelocity.x < -maxVelocity)
    {
        playerVelocity.x = -maxVelocity;
    }


    if (playerVelocity.y > maxVelocity)
    {
        playerVelocity.y = maxVelocity;
    }
    else if (playerVelocity.y < -maxVelocity)
    {
        playerVelocity.y = -maxVelocity;
    }

//    Point pos = mGravityBall->getPosition();
//    pos.x += playerVelocity.x;
//    mGravityBall->setPosition(pos);

}

I think nothing wrong with code as its working perfect in iphoneX. Why not its tilted in iPhone6 ?


Solution

  • The accelerometer API operates along fixed axes. If you want to treat it as if it's always in landscape, you'll need to use the y axis instead.

    https://developer.apple.com/documentation/coremotion/getting_raw_accelerometer_events