Search code examples
javaandroidlibgdxviewport

LibGdx-ViewPort width and height does not match for some devices


I am using a Viewport for my libGdx landscape game like this.

public static final int WORLD_WIDTH = 1280;
public static final int WORLD_HEIGHT = 800;

camera = new OrthographicCamera();
float aspectRatio = Constants.WORLD_WIDTH / Constants.WORLD_HEIGHT; 

ViewPort viewPort = new FillViewport(WORLD_WIDTH * aspectRatio,WORLD_HEIGHT, camera);

I am using all positions in terms of this width and height.

It is working fine in all devices except device that have screen resolution greater than 1300. In device that have greater resolution than 1300,only middle part of the game is visible.I tried using stretched viewport for the greater resolution device,but it is giving all game elements stretched.

How can I make my game working in all devices fine?Do I need to change the viewport?


Solution

  • Finally I made it work. I am not sure whether this is the correct way to solve such problems. I did it like this;

        camera = new OrthographicCamera();
        if(screenHeight>1300)
        {
    
            Constants.WORLD_WIDTH=1280;
            Constants.WORLD_HEIGHT=960;
    
        }
        else{
            Constants.WORLD_WIDTH=1280;
            Constants.WORLD_HEIGHT=800;
    
        }
         viewPort = new FillViewport(Constants.WORLD_WIDTH, Constants.WORLD_HEIGHT, camera);
         viewPort.apply();
    

    I used a viewPort width of 1280x960 for all greater resolution devices while keeping 1280x800 resolution for all other devices that has screen width less than 1300. While drawing background I used viewport width and height to set the size like this.

    bgSprite=new Sprite(bgTexture);
        bgSprite.setPosition(Constants.BG_X,Constants.BG_Y);
    bgSprite.setSize(game.viewPort.getWorldWidth(),game.viewPort.getWorldHeight());
    

    Not sure this the right way,but doing this solved my problem.