LibGDX’s Scene2D and TiledMap

Posting a short tutorial because I had some trouble finding the right resources for this and I hope that my post will help others should they come across the same difficulties.

I wanted to use LibGDX’s Scene2D API with a TiledMap. Before I used Tiled I just had a simple image as a “map” and that worked to figure out how to move the camera and basic collision detection (based on other actors in the stage), but it is rather lengthy  and a hassle to maintain/extend.

How to use Scene2D with TiledMap

tiledMap = new TmxMapLoader().load("maps/island.tmx");
mapRenderer = new OrthogonalTiledMapRenderer(tiledMap, 1);

First we load the TiledMap into our program and instantiate our renderer.

mapRenderer.setView((OrthographicCamera) stage.getCamera());

We then bind set the view of the TiledMap to the stage’s camera. This is one thing I forgot and I saw nothing (aside from my debugging bounding boxes).

mapRenderer.render();
stage.act();
stage.draw();

To conclude with drawing the map and the stage. The order is important, unless you want to only see your map…

Of course, this is only rendering, so let me move on to:

Collision Detection

Before I added a TiledMap, my collision detection was just my game looping through the actors and if it had a bounding box overlap, it would detect a collision. Combining this method with the use of an objectlayer in Tiled which has rectangles defining bounding boxes for solid things resulted in the following code:

public boolean collision(Actor movingObject) {
Rectangle rectangleMovingObject = new Rectangle(movingObject.getX(), movingObject.getY(), movingObject.getWidth(), movingObject.getHeight());
for (Actor actor : world.getChildren()) {
if (actor == movingObject) {
continue;
}
if (actor instanceof Image) {
continue;
}
Rectangle rectangle = new Rectangle(actor.getX(), actor.getY(), actor.getWidth(), actor.getHeight());
if (Intersector.overlaps(rectangle, rectangleMovingObject)) {
return true;
}
}

MapObjects layerObjects = layer.getObjects();
for (RectangleMapObject rectangleObject : layerObjects.getByType(RectangleMapObject.class)) {

Rectangle rectangle = rectangleObject.getRectangle();
if (Intersector.overlaps(rectangle, new Rectangle(movingObject.getX(), movingObject.getY(),16,16))) {
Log.d(rectangle + " " + movingObject.getX() + " " + movingObject.getY());
return true;
}
}

return false;
}

As you can see, this code constantly asks the layer for its objects. I’m leaving it in this quick and dirty way because my game only has one map (and one other actor) as of yet, but you should clean that code up if you plan on using it.

Conclusion

As said, a simple tutorial. Probably a bit unnecessary, but I wanted to see it spelled out this clearly so that I won’t waste another hour or three on this.

Resources used

  • libgdx version 0.9.9
  • Tiled version 0.9.1