1
\$\begingroup\$

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;
        img = new Texture(Gdx.files.internal("badlogic.jpg"));
        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

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Thank you so much! I didn't knew that you had to update and apply the viewport :( \$\endgroup\$ Commented May 4, 2018 at 13:30
  • \$\begingroup\$ @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. \$\endgroup\$
    – Charanor
    Commented May 4, 2018 at 13:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .