Search code examples
javaandroidlibgdxorientation

Orientation always result to portrait (Motion Controls in libgdx)


My code is as follows:

Input.Orientation orientation = Gdx.input.getNativeOrientation();
message = "";
switch (orientation) {
    case Landscape:
        message += "Landscape\n";
        break;
    case Portrait:
        message += "Portrait\n";
        break;
    default:
        message += "Whatever\n";
}

The above code(inside render method) always indicates that the device is in portrait mode, even when i rotate the device! What am I doing wrong? How can I accurately detect whether the device is in Portrait or Landscape mode?


Solution

  • The getNativeOrientation() doesn't return current orientation of device, it is returning something like whether the screen is landscape or portrait when you hold it properly (on most phones it should return portrait, but I guess on tablets and phones like HTC ChaCha it returns landscape).

    There are several ways to get current orientation:

    • Recommended: Use Gdx.input.getRotation() which returns rotation of device in degrees (0, 90, 180, 270) with respect to its native orientation. Use it with getNativeOrientation() and you should be able to get right orientation for all devices.

    Note: it gives you orientation of current state of application, not orientation of device as physical object. So if you have a android:screenOrientation="landscape" in your manifest, this method will always return landscape.

    Example usage:

    int rotation = Gdx.input.getRotation();
    if((Gdx.input.getNativeOrientation() == Input.Orientation.Portrait && (rotation == 90 || rotation == 270)) || //First case, the normal phone
            (Gdx.input.getNativeOrientation() == Input.Orientation.Landscape && (rotation == 0 || rotation == 180))) //Second case, the landscape device
        Gdx.app.log("Orientation", "We are in landscape!");
    else
        Gdx.app.log("Orientation", "We are in portrait");
    
    • Create interface on native side (Android), pass it to game.

    • If you are using this as controls maybe you should use accelerometer or gyroscope instead