Search code examples
javaandroidorientationlibgdx

Change game from portrait to landscape dynamically


I have multiple classes that implement Screen.

I want to, say, have the Main Menu screen portrait, then the Play Screen landscape. Is there anyway of changing the orientation dynamically?

I thought I could just start another Activity and have the Play Screen extend Game. And the new Activity would intialize the Play Screen. But it appears that you can't call startActivity or the like, obviously, as LibGDX is platform independent.

I use Gdx.graphics.getWidth() and Gdx.graphics.getHeight() to align Sprites and Actors, so it looks "right" on different devices.

I've also tried swapping the Gdx.graphics.getWidth() and Gdx.graphics.getHeight(), respectively, but can't seem to get the position of sprites and actors correct.

Also, in my manifest I have orientation="landscape".

Here are some images that should make more sense.

So this is my Main Menu in landscape: enter image description here

And this is my Main Menu in portrait:

enter image description here

The position and size of Actors and Sprites are all based on Gdx.graphics.getWidth() and Gdx.graphics.getHeight(). The only thing that changes between the two images is orientation="landscape" and orientation="portrait" in my manifest.

Now I want my Main Menu in portrait but the Play Screen, where the game is on, should be in landscape.

I initially started working on the Play Screen and the sizes and positions where set based on orientation="landscape", and now that I am working on the Main Menu it is based on orientation="portrait". Hence why I want to change the orientation dynamically.


Solution

  • You should not have multiple Activities. To learn how to switch the orientation programmatically you can have a look at this link.

    As you said, LibGDX is platform-independent. That's why you cannot access your Android-Activity from your "core" code. To learn how to workaround that, have a look at Interfacing with platform specific code.

    When you call your interface to change the orientation from your game when doing a Screen transition, LibGDX will automatically call resize(width, height) with the new values and you can align your Stage and so on according to the new values.