Search code examples
javalibgdx

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?


Solution

  • 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);