Search code examples
libgdxviewport

Preffered viewPort to dealing with textButton libgdx


i work with a new game , i have create 2 camera one camera for real world and another (GUI) camera for a static resolution (800 x 480)

private void init () {

    camera = new OrthographicCamera(16,9);
    camera.position.set(0, 0, 0);
    camera.update();

    cameraGUI = new OrthographicCamera(800,480);
    cameraGUI.position.set(0, 0, 0);
    cameraGUI.update();

And i want to use a textButton in my game , so i've create a new stage using a new fitViewPort

    fitViewPort=new FitViewport(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
    gameController.stage=new Stage(fitViewPort);

then i create my textButtons using my bitmap font and i try it on the Desktop , and it's great desktop

but when i try another device , the position is not the same Tablet

then i think for using the cameraGui Width and height for my view port , the font is very bad stretched

any help please :(


Solution

  • Don't create a special camera for GUI, because viewport already has a camera.

    Make your viewport width and height fixed, in your case:

    fitViewPort = new FitViewport(800, 480);
    gameController.stage = new Stage(fitViewPort);
    

    And then just add actors to stage and draw it just by calling method

    gameController.stage.draw();
    

    Note: Remember to add gameController.stage.getViewport().update(width, height); in your resize method.

    Edit: Using small fixed viewport (800x480 is small) will cause scaling, that is why the font is stretched. For example if you run a 800x480 layout on 1920x1080 display it will be scaled by 225%.

    What you can do is generate a font with big size and the set scale to its data fe. bitmapFont20.getData().setScale(0.5F); (in this case font is generated by FreeTypeFontGenerator with size 40). Using this trick you will be able to get a great results. The proof is below. It is viewport of 640x360F * (float) Gdx.graphics.getHeight() / (float) Gdx.graphics.getWidth() scaled to 1920x1080. Font is generated with size 72 and then data scale is set to 0.5F

    Method proff

    Here is the same text, but without modified data scale.

    Without method