简体   繁体   中英

LibGDX - Centering Orthographic Camera

so I'm working on a game where I would like to have the camera in game centered on the middle of the screen for all device lengths. I hope this picture can better explain what I'm trying to achieve. I have tried setting the position of the camera but that hasn't worked for me.

    scrnHeight = Gdx.graphics.getHeight();
    if (scrnHeight <= HEIGHT) {

        cam.setToOrtho(false, 480, 800);
    } else {
        cam.setToOrtho(false, 480, scrnHeight);
    }

    //This is the part that seems to be giving me all the issues
    cam.position.set(cam.viewportWidth/2,cam.viewportHeight/2, 0);
    cam.update();

    Gdx.input.setInputProcessor(this);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    gsm.update(Gdx.graphics.getDeltaTime());
    gsm.render(batch);

    batch.begin();
    batch.draw(border, -(border.getWidth() - WIDTH) / 2, -(border.getHeight() / 4));
    batch.end();

I don't know if I'm giving it the wrong coordinates when I'm setting the position or what is happening that causes the lack of vertical centering. Any help would be much appreciated.

The orthographic camera position in LibGDX means position in-game , not on the device screen, therefore changing it won't actually move the game screen on the device.

Therefore, you use the camera position to move and position the camera in-game.
For example, in response to player input movement:

if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
    cam.translate(-3, 0, 0); // Moves the camera to the left.
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
    cam.translate(3, 0, 0);  // Moves the camera to the right.
}

As you can see, we are moving the camera in-game, left and right according to the player's input.

However, your code has a few more issues like not setting the batch projection matrix:

batch.setProjectionMatrix(cam.combined);

And resetting the camera position to the center of the viewport each frame:

// Don't run this each frame, it resets the camera position!
cam.position.set(cam.viewportWidth/2,cam.viewportHeight/2, 0);
cam.update(); // <- However, you must run this line each frame.


Finally, centering the LibGDX app on the device screen should be done outside of Libgdx, otherwise, if you intend to use the spare screen for the same LibGDX app, then you should create another camera to work full screen and render it before the actual game camera, usually used for HUD and such...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM