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
I'll recommend ExtendViewprot to use, because it keeps the world aspect ratio without black bars by extending the world in one direction. Use all positions in terms of world width and height not screen width and height and resize viewport in resize method according to your device width and height.
Your resources size should be in the respect of world width and height.
public class MyGdxGame extends ApplicationAdapter {
Stage stage;
public static final int WORLD_WIDTH = 800;
public static final int WORLD_HEIGHT = 480;
@Override
public void create() {
ExtendViewport extendViewport=new ExtendViewport(WORLD_WIDTH,WORLD_HEIGHT);
stage=new Stage(extendViewport);
//logical pixels of your current device, device specific
//float w=Gdx.graphics.getWidth(); //screen width
//float h=Gdx.graphics.getHeight();// screen height
Image image=new Image(new Texture("badlogic.jpg"));
image.setPosition(WORLD_WIDTH/2,WORLD_HEIGHT/2, Align.center); //consider world width and height instead of screen width and height
stage.addActor(image);
stage.setDebugAll(true);
}
@Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(0,0,0,1);
stage.act();
stage.draw();
}
@Override
public void resize(int width, int height) {
stage.getViewport().update(width,height);
stage.getCamera().position.set(WORLD_WIDTH/2,WORLD_HEIGHT/2,0);
stage.getCamera().update();
}
@Override
public void dispose() {
stage.dispose();
}
}
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.