Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Libgdx Orthographic Camera initial position

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

enter image description here

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());
}
like image 790
1000Suns Avatar asked Feb 20 '14 16:02

1000Suns


2 Answers

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)
}
like image 163
jpm Avatar answered Oct 16 '22 03:10

jpm


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);
like image 29
noone Avatar answered Oct 16 '22 02:10

noone