Search code examples
androidandroid-studiolibgdxscreen-resolutionaspect-ratio

Keep the aspect ratio in libGDX


I'm making a game for android using libgdx and I want the game look good (with the same proportion) on different screens of smartphones, but not achievement. In a device the picture looks normal and another is very small.

I used viewports and OrthographicCamera but I don't see good results. Maybe what I'm doing wrong.

Currently I have this code (excerpt):

public class PlayScreen extends BaseScreen {

    private Stage stage;
    private FaceActor faceActor64;
    private Texture faceTexture64;

    private  int sw;
    private int sh;

    public PlayScreen(MainGame game) {
        super(game);
        faceTexture64 = new Texture("images/all64.png");
    }

    @Override
    public void show() {
        sw = Gdx.app.getGraphics().getWidth();
        sh = Gdx.app.getGraphics().getHeight();

        stage = new Stage(new FitViewport(sw, sh));

        faceActor64 = new FaceActor(faceTexture64);
        faceActor64.setBounds(150, 150, 64, 64);
        stage.addActor(faceActor64);

        Gdx.input.setInputProcessor(stage);

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0,0,0,1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(delta);
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {
        stage.getViewport().update(width, height, true);
    }

    @Override
    public void hide() {
        stage.dispose();
    }

    @Override
    public void dispose() {
        faceTexture64.dispose();
    }
}

I'm using an image of 64px.

Result in a smartphone of 480x800.

Result in a smartphone of 1080x1920.

Any idea how to fix it?


Solution

  • What you are doing there is this:

    For a 720x1280 device you are setting the view of your game world to 720x1280 and for a 1080x1920 device you are setting it to 1080x1920. You assets most likely do not change in size so the more pixels a device has the more it will show of your game world. I always tell people to forget about pixels, unless they want a pixel perfect game and that is what you are creating if you do not resize your assets, a pixel perfect game world.

    If you think about it, your game does not even need to know about the device. It just needs to know how much of your game world to render in that FitViewport. So let's say I have a tile game and my tiles have a size of 1x1 units. If I would want to show 16 tiles vertically and 9 horizontally I would setup my FitViewport as new FitViewport(9, 16). This would fill up the screen on most devices since they often have a aspect ratio of 16:9.