Search code examples
javalibgdxtiled

how to get the x and y position of a tiled map object with Libgdx?


I've been searching around the internet for a while now and literally nothing has helped, but I've been trying to figure out how to get the x and y position of a Tiled map object.

I've tried using map1.getLayers().get(3).getObjects().get(1).getX() to get the x position but the getX() method returns an error: Cannot resolve method 'getX' in 'MapObject'.

Is there another method I can use or should I just change my approach entirely?


Solution

  • map1.getLayers().get(3).getObjects().get(1) will return a MapObject, that doesn't define a getX() method. Depending on the type of the MapObject you need to cast it, to get it's position. E.g. if it's a RectangleMapObject you can do this:

    MapObject mapObject = map1.getLayers().get(3).getObjects().get(1);
    if (mapObject instanceof RectangleMapObject) {
      RectangleMapObject rectangleMapObject = (RectangleMapObject) mapObject;
      // now you can get the position of the rectangle like this:
      Rectangle rectangle = rectangleMapObject.getRectangle();
      float x = rectangle.getX();
      float y = rectangle.getY();
      // TODO maybe add width and hight ...
    }
    

    If it's no RectangleMapObject you need to check the other subclasse of MapObject.