Search code examples
javaoopinheritancelibgdx

libgdx how to set position of camera from another non-main class? [Java]


I think it's very basic java question. I have two classes: Main and InputManager class:

public class InputManager implements InputProcessor {
    Main main = new Main();
    @Override
    public boolean keyDown(int keycode) {
        switch (keycode) {
            case Keys.A:
                System.out.println(main.cam.position.set(1, 0, 0));
                break;
        }
        return false;
    } // etc...

The Main class has public OrthographicCamera cam; field, I just want to set position of cam from InputManager class. How this can be done? Pressing "A" shows me "Nullpointer exception". Can't find any examples :(


Solution

  • Main main = new Main();
    

    According to your code cam of Main class is null because you're initialising camera inside create() method that is lifecycle method of ApplicationListener, called when the Application is first created..

    Instead of constructing new Object use already created by this :

    Main main=  (Main)Gdx.app.getApplicationListener();