简体   繁体   中英

LibGDX - How to center an Isometric Tiled Map on screen?

I've been tinkering around with LibGDX for a few days now. I've managed to render an Isometric Tiled Map onto the screen but I just can't seem to figure out how to center it properly. Here's the code:

public class PlayScreen implements Screen {

    private TiledMap map;
    private IsometricTiledMapRenderer isometricRenderer;
    private OrthographicCamera camera;

    public void createUI() {
        // Load map from tiled .tmx file.
        map = new TmxMapLoader().load("arena1/arena1.tmx");

        // Setup isometric renderer and camera.
        isometricRenderer = new IsometricTiledMapRenderer(map);
        camera = new OrthographicCamera();
    }

    @Override
    public void show() {
        Gdx.gl.glClearColor(0, 0, 1, 1);
        createUI();
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        isometricRenderer.setView(camera);
        isometricRenderer.render();
    }

    @Override
    public void resize(int width, int height) {
        camera.viewportWidth = width;
        camera.viewportHeight = height;
        camera.update();
    }

    @Override
    public void pause() {}

    @Override
    public void resume() {}

    @Override
    public void hide() {}

    @Override
    public void dispose() {
        map.dispose();
        isometricRenderer.dispose();
    }

}

And here is what I get:

在此处输入图片说明

Thank you in advance!

Tiled map hasn't setPosition method or something like this. So what you should do is move your camera.

Call this in your render method to move your camera by WASD:

private void cameraController(Camera camera){

    if (Gdx.input.isKeyPressed(Input.Keys.W)) {
       camera.translate(0, 10, 0);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.S)) {
       camera.translate(0, -10, 0);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.A)) {
       camera.translate(-10, 0, 0);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.D)) {
       camera.translate(10, 0, 0);
    }
}

You can also change 10 to speed which you want.

Or if you don't want to move it by WASD you can just set position directly.

camera.setPosition(x, y, z); 

Managed to do it with

camera.position.set(768, 0, 0);

768 is half the width of the map.

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