Kevin Bryan
Kevin Bryan

Reputation: 1858

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

Upvotes: 0

Views: 60

Answers (2)

Peter R
Peter R

Reputation: 1034

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

Upvotes: 1

JusMe
JusMe

Reputation: 288

In Java coordinates start in the upper left corner (0,0). On a 100 x 100, (100,0) would be upper right, and (0, 100) would be lower left. So the behavior you are seeing is expected.

http://inetjava.sourceforge.net/lectures/part2_applets/InetJava-2.1-2.2-Introduction-to-AWT-and-Applets_files/image001.gif

Upvotes: 1

Related Questions