Search code examples
javalibgdxscreen-resolutionscreen-size

libgdx using percentage for images


I'm making a game sort of like flappy bird, but it works on landscape mode, to make it fair so that people with bigger screens don't have an advantage I change my images to screen % for example the bird will be 10% of screen height, so it will be the same in all screens, the question is, is this a good idea or is there any other way?


Solution

  • You don't need to use percentages. If you are using libgdx, you can (and should) use a predefined viewport size, so the screen resolution is handled by the library and not you.

    You can achieve this using a camera, setting a fixed height, and calculating the width:

    HEIGHT = 10;
    WIDTH = (Gdx.graphics.getWidth()/Gdx.graphics.getHeight())*HEIGHT;
    
    camera = new OrthographicCamera();
    camera.setToOrtho(false, WIDTH, HEIGHT);
    

    this way, your height will be 10 units. And the width will be caculated by the screen x-y ratio.

    the bird will be 10% of screen height

    Then your bird will be 1 unit size (height/10).

    If you want both sides to be fixed (so noone sees more in the width). Its even easier, but your images won't keep their ratio, they will be stretched in both axis.

    HEIGHT = 10;
    WIDTH = 15;
    
    camera = new OrthographicCamera();
    camera.setToOrtho(false, WIDTH, HEIGHT);