Orientation always leads to portrait orientation (motion control 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 code above (internal rendering method) always means that the device is in portrait mode, even if I rotate the device! What exactly am I doing wrong? How can I accurately detect whether a device is in portrait or landscape mode?
Solution
getNativeOrientation()
does not return the current orientation of the device, it returns some information such as whether the screen is landscape or portrait when you hold it correctly (on most phones it should return to portrait, but I guess on tablets and phones like HTC ChaCha it will return to landscape).
There are several ways to get the current direction:
- Recommended: Use
Gdx.input.getRotation()
to return the degree of rotation of the device relative to its original orientation (0, 90, 180, 270). Use it withgetNativeOrientation()
and you should be able to get the right orientation for all devices.
Note: It gives you the orientation of the current application state, not the orientation of the device as a physical object. So, if you have android:screenOrientation=
“landscape” in your list, this method will always return the 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 the interface on the native side (Android) and pass it to the game.
If you’re using it as a control, maybe you should use accelerometer or gyroscope