Patrick Reck
Patrick Reck

Reputation: 11374

Sprite positioning using mouse coordinates

I am trying to move a sprite to the mouse position on click.

However, the coordinates I am getting from Gdx.input.getX()and Gdx.input.getY() is relative to the top left corner, and the setPosition() method of Sprite is relative to the bottom left corner.

Why is this so, and how do I position my sprite where the mouse was clicked?

Upvotes: 0

Views: 423

Answers (1)

Tenfour04
Tenfour04

Reputation: 93581

Screen coordinates come from Android and use a Y-down frame of reference. Cameras in libgdx by default use a Y-up frame of reference (because OpenGL by convention also uses a Y-up frame of reference).

If you prefer the Y-down frame of reference, you can use camera.setToOrtho(true); method to flip it upside down. You might prefer this if coming from a Flash background.

But in general, the safe way to translate screen coordinates from a touch into the camera's coordinate system is to do the following. This will work regardless of what platform you're on and whatever coordinate system you chose for the camera. For example, for some types of games, you wouldn't even be using a camera that matches the screen resolution, but you'd still want screen coordinates converted to camera coordinates. Also, if you have a camera that moves around the world, this will automatically change the touch point to world coordinates.

tempVector3.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(tempVector3);
//now tempVector3 contains the touch point in camera coordinates.

It uses Vector3 because this also works for 3D cameras.

Upvotes: 2

Related Questions