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

前端 未结 2 1309
日久生厌
日久生厌 2020-12-12 05:36

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         


        
2条回答
  •  [愿得一人]
    2020-12-12 06:14

    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();
        }
    }
    

提交回复
热议问题