Search code examples
javalibgdxviewportviewport-units

libgdx how to get height and width in world units


I am trying to understand the use of viewports in Libgdx I have the variables V_WIDTH = 800 and V_HEIGHT = (V_WIDTH / (4f/3f)) so V_HEIGHT = 600. This is how I initialize and update my viewport:

// init viewport (in the constructor):
    viewport = new FitViewport(NoThanksClient.V_WIDTH, NoThanksClient.V_HEIGHT);

    // in the resize method:
    viewport.update(width,height, true);

I have a texture of a green rectangle and I am trying to draw it on the left top corner. this is how I done it:

        batch.draw(
            frameTexture,
            0,
            viewport.getScreenHeight() - FRAME_TEXTURE_HEIGHT,
            FRAME_TEXTURE_WIDTH,
            FRAME_TEXTURE_HEIGHT);

and it's all working good. but when I resize my screen the texture (frameTexture) is getting out or in from the screen. why isn't it stay at the corner? and what can I do to make it stay?


Solution

  • Well, your viewport also needs a camera. A camera is what displays the game to the screen. The viewport is what manages the size of the camera. When it comes to drawing with the batch, you need to link the batch to that camera. This is how you should be initializing your viewport:

    private Camera camera;
    private Viewport viewport;
    
    public void create() {
         camera = new OrthographicCamera();
         viewport = new FitViewport(NoThanksClient.V_WIDTH, NoThanksClient.V_HEIGHT, camera);
    }
    

    This set the camera that the viewport will be manipulating to the OrthographicCamera. You can use any child class of Camera as well.

    Your resize method is fine, and you just have to add one more line to your rendering method, right before you draw.

    batch.setProjectionMatrix(camera.combined);
    batch.draw(
               frameTexture,
               0,
               viewport.getScreenHeight() - FRAME_TEXTURE_HEIGHT,
               FRAME_TEXTURE_WIDTH,
               FRAME_TEXTURE_HEIGHT);
    

    Setting the projection matrix will make sure that the batch draws to that camera, and thus through the viewport that you created. I hope this helps, let me know if you have any more questions. You can find more information about view ports here.