# LibGdx Camera Movement

I just started learning a few things about libGdx and i don't really understand how the camera works because i've created a camera, then set the camera position to viewport.getWorldWidth()/2 and viewport.getWorldHeight()/2 and then i would like to draw a image at 0,0 or where the camera starts drawing but i don't really understand why it's not working.Here's the code:

public class PlayScreen implements Screen {

private OrthographicCamera cam;
private Viewport viewport;
private MainClass mainClass;
Texture img;

public PlayScreen(MainClass mainClass){
this.mainClass = mainClass;
cam = new OrthographicCamera();
viewport = new StretchViewport(400, 200, cam) ;
cam.position.set(viewport.getWorldWidth()/2, viewport.getWorldHeight()/2, 0);

}

@Override
public void show() {

}

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

if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
cam.position.x += 100 * delta;
System.out.println(cam.position.x);
}

if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
cam.position.x -= 100 * delta;
System.out.println(cam.position.x);
}

cam.update();
mainClass.batch.setProjectionMatrix(cam.combined);

mainClass.batch.begin();
mainClass.batch.draw(img, 0  , 0); //here i'm not sure what position should it be
mainClass.batch.end();
}


The output it's just a blank window, i don't understand where it starts drawing

This is because you are not updating and applying your Viewport before drawing. The best place to do this would be in the resize(width, height) method like so:

@Override
public void resize(int width, int height) {
// Update the viewport so it properly converts coordinates
viewport.update(width, height);
// Actually apply the viewport. True means center camera.
viewport.apply(true);
}


Since we're calling apply with true we also don't have to center the camera manually in the constructor.

• Thank you so much! I didn't knew that you had to update and apply the viewport :( – Player May 4 '18 at 13:30
• @Player No problem :) I had this problem as well when I started using LibGdx! If it fixed your problem make sure to tick the checkbox to the left to signal to future readers that it solved your issue. – Charanor May 4 '18 at 13:39