简体   繁体   中英

Libgdx Orthographic Camera initial position

I would like the camera to be positioned correctly but I am getting the result below:

在此输入图像描述

It seems like when I resize the window, the map does not get rendered properly. Why does that happen?

Code:

public void render(float delta){
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    camera.update();
    mapRenderer.setView(camera);
    mapRenderer.render(background);
    mapRenderer.render(foreground);
    shapeRenderer.setProjectionMatrix(camera.combined);

    //draw rectangles around walls
    for(MapObject object : tiledMap.getLayers().get("walls").getObjects()){
        if(object instanceof RectangleMapObject) {
            RectangleMapObject rectObject = (RectangleMapObject) object;
            Rectangle rect = rectObject.getRectangle();
            shapeRenderer.begin(ShapeType.Line);
            shapeRenderer.rect(rect.x, rect.y, rect.width, rect.height);
            shapeRenderer.end();
        }
    }
    //done drawing rectangles
}

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

@Override
public void show(){
    //call the tile map here
    //I believe this is called first before render() is called
    tiledMap = new TmxMapLoader().load("data/mapComplete.tmx");
    mapRenderer = new OrthogonalTiledMapRenderer(tiledMap, 1f);

    //initiate shapeRenderer. Can remove later
    shapeRenderer = new ShapeRenderer();
    shapeRenderer.setColor(Color.RED);

    camera = new OrthographicCamera();
    camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}

This should center the camera at the viewport of the game.

@Override
public void resize(int width, int height) {
    camera.viewportWidth = width;
    camera.viewportHeight = height;
    camera.position.set(width/2f, height/2f, 0); //by default camera position on (0,0,0)
}

You do not set the position of the camera anywhere. Thus it is looking at (0, 0) by default (which means (0, 0) will be in the center of your screen). The TiledMapRenderer renders the bottom left corner of the map at (0, 0) which means that it will fill the top right quadrant of your screen. That's what you see in your screenshot.

To set it to the center of the map, you could do something like the following:

TiledMapTileLayer layer0 = (TiledMapTileLayer) map.getLayers().get(0);
Vector3 center = new Vector3(layer0.getWidth() * layer0.getTileWidth() / 2, layer0.getHeight() * layer0.getTileHeight() / 2, 0);
camera.position.set(center);

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