Alf
Alf

Reputation: 1295

Get screen position of Image (or actor) in Libgdx Stage

I have this piece of code:

Image myImage = new Image(new Texture("data/file.png"));

How to get myImage position on a screen? I tried myImage.getX() and myImage.getImageX() both always return 0.0. What's wrong?

Upvotes: 4

Views: 8014

Answers (3)

Emperor Orionii
Emperor Orionii

Reputation: 752

Now Actors have localToScreenCoordinates to get what you need in one call:

Vector2 screenPosition = myImage.localToScreenCoordinates(new Vector2(0f, 0f))

Upvotes: 1

user2010539
user2010539

Reputation:

Just a guess!!! - Moving the image & checking for position but getX() returning 0.0 might be because its the camera which moves & produces the movement effect, image may havenot been moved at all & tsayed at the initial position of 0.0 (i think this might be the thing you are missing)

Upvotes: 1

P.T.
P.T.

Reputation: 25177

I believe getX() and getY() on an Actor are relative to their parent container, so you'll need to convert the coordinates to "stage" coordinates, and then from there to "screen" coordinates. (I think there is an easier way to do this, so there may be a better answer out there).

Image myImage = ...;
Vector2 coords = new Vector2(myImage.getX(), myImage.getY());
myImage.localToStageCoordinates(/*in/out*/coords);
myImage.getStage().stageToScreenCoordinates(/*in/out*/coords);

System.out.println("Image X " +myImage.get()+ " maps to screen " +coords.x);

Upvotes: 9

Related Questions