Libgdx Orthographic Camera initial position

限于喜欢 提交于 2019-12-07 05:06:20

问题


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());
}

回答1:


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)
}



回答2:


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);


来源:https://stackoverflow.com/questions/21913894/libgdx-orthographic-camera-initial-position

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!