Picking up Game Objects from a Tiled Map

Question

(asked by Zareh Gorjian)

"[...] How would you do things like a player/sprite picking up an object (like some treasure) on the map? [...] There is also the matter of making that treasure object disappear when the player picks it up. How can you do this? for example put a grass tile(s) where the treasure tile(s) used to be."

You have multiple options to create objects that a player can pick up:

Tile with custom properties

This is usually the easier thing to do. If you want pick the object up, set another tile (e.g. an air or grass tile) in its spot: cell.setTile(airTile)

Map Objects

You can get the MapObject using MapLayer#getObjects(). The are a few types of objects that it could be an instance of:

  • RectangleMapObject
  • EllipseMapObject
  • CircleMapObject
  • PolygonMapObject
  • PolylineMapObject
  • TextureMapObject (not created by the TmxMapLoader)

Using the instanceof operator you can check which kind of MapObject you have and then cast it to its actual type. You can then use all of its methods to create an instance of your own game object class. For example (Coin is your class):

for(MapObject object : layer.getObjects()) {
    if(object instanceof RectangleMapObject) {
        MapProperties props = object.getProperties();
        if(props.containsKey("type") && props.get("type", String.class).equals("coin")) {
            RectangleMapObject rectObj = (RectangleMapObject) rectObj;
            Rectangle rect = rectObj.getRectangle();
            Coin coin = new Coin();
            coin.setPosition(rect.getX(), rect.getY());
            coin.setSize(rect.getWidth(), rect.getHeight());
            gameObjects.add(coin);
        }
    }
}

Feedback and Knowledge Base