Search code examples
javacameralibgdxcoordinates

How to setup camera properly?


On my class I'm implementing ApplicationListener, so on my create method this is what I do:

public void create(){
camera=new Camera();
camera.setToOrtho(false,screenW,screenH);
}

//then on the render method:
public void render(){
camera.update();
}

But then when I use Gdx.input.getY() the result is reversed, when I go up the Y coordinate is less and when I go down the it gets higher.For better understanding:

enter image description here


Solution

  • Have a look at the camera class and the unproject method. That should translate between screen coordinates and world coordinates. (Probably more efficient way to do this, but for illustration):

    float x = Gdx.input.getX();
    float y = Gdx.input.getY();
    float z = 0.0f;
    Vector3 screenCoordinates = new Vector3(x, y, z);
    Vector3 worldCoordinates = camera.unproject(screenCoordinates);
    

    Then use the worldCoordinates vector for whatever you need it for.

    EDIT: Added small working example and screenshot. My screen capture didn't capture the mouse, thus the red "star". But this simple app displays y coordinates in "initial" and "unprojected" coords as you move the mouse around the screen. Try it for yourself. I think this is what you are getting at, no?

    import com.badlogic.gdx.ApplicationListener;
    import com.badlogic.gdx.Gdx;
    import com.badlogic.gdx.graphics.OrthographicCamera;
    import com.badlogic.gdx.math.Vector3;
    
    public class SimpleInputCoords implements ApplicationListener {
       private OrthographicCamera camera;
    
       @Override
       public void create() {
          camera = new OrthographicCamera();
          camera.setToOrtho(false, 800, 480);
       }
    
       @Override
       public void render() {
           int x = Gdx.input.getX();
           int y = Gdx.input.getY();
           int z = 0;
           System.out.println("UnmodifiedYCoord:"+y);
    
           Vector3 screenCoordinates = new Vector3(x, y, z);
           Vector3 worldCoordinates = camera.unproject(screenCoordinates);
           System.out.println("UnprojectedYCoord:"+worldCoordinates.y);
       }
    
       @Override
       public void dispose() {
       }
    
       @Override
       public void resize(int width, int height) {
       }
    
       @Override
       public void pause() {
       }
    
       @Override
       public void resume() {
       }
    

    }

    enter image description here