Search code examples
libgdxgame-physicsphysicsgame-development

Why camera in stage is not required to be centered in libgdx


How stage camera is able to see full stage view if (0,0) of the camera is located by default at (0,0) of stage. if update method for viewport is not called nor camera position set method is called.


Solution

  • If you look into the Stage Constructor:

    public Stage (Viewport viewport, Batch batch) {
        if (viewport == null) throw new IllegalArgumentException("viewport cannot be null.");
        if (batch == null) throw new IllegalArgumentException("batch cannot be null.");
        this.viewport = viewport;
        this.batch = batch;
    
        root = new Group();
        root.setStage(this);
    
        viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
    }
    

    We see on the last line viewport.update() with the width, height and true as parameters. Let's look at this viewport.update() method:

    public void update (int screenWidth, int screenHeight, boolean centerCamera) {
        apply(centerCamera);
    }
    

    Now let's look on the apply() method. We know centerCamera is true:

    public void apply (boolean centerCamera) {
        HdpiUtils.glViewport(screenX, screenY, screenWidth, screenHeight);
        camera.viewportWidth = worldWidth;
        camera.viewportHeight = worldHeight;
        if (centerCamera) camera.position.set(worldWidth / 2, worldHeight / 2, 0);
        camera.update();
    }
    

    And here we find the answer: if (centerCamera) camera.position.set(worldWidth / 2, worldHeight / 2, 0);

    The stage centered the camera position on her own.