# libGDX Tiled Box2D - tile collisions

## Intro

This is the object layer sub page of the example. If you are new to the series, click here to access the main page first.

## Map Setup

1. Open tiles settings
2. Open the tile collision editor
3. Draw the tile collisions. Hold ctrl to snap to corners.

### Comparison

#### Object layer #### Tile collisions As you see, the object layer version creates a lot less rectangles, therefore is faster to parse and might work better. The tile collision version however is automated and you don’t need to care about creating collisions shapes.

## Implementation

Now for the fun part!

Let’s iterate through each tile and check if it has a collision object.

Then we’ll need to get the actual shape in the map object.
This is done by checking which class it actually is (then converting to it), and calling `.getXXX()` on it.

## Box2d body creation

Now inside each if …

### Rectangle

This is a bit more complicated compared to the object layer way.

In Tiled every object’s x/y coordinates are bottom left. Sadly Box2D uses center coordinates. Therefore we’ll need to some magic to convert between them.

1. Convert `x * tileSize` so we get the bottom left “tile pixel coordinates” of the tile.
2. Add `tileSize / 2f` to that, so we’re centered on the tile.
3. Then we’ll do some magic to get the proper offset `+ rectangle.getY() - (tileSize - rectangle.getHeight()) / 2f`

`.setAsBox()` accepts half width/height parameters, therefore we’ll need to half the width/height.

### Circle

Here we have another little problem, Tiled allows ellipses, Box2D only circles. Therefore we’ll need to check if the ellipse is actually a circle.

Additionally ellipse coordinates are already centered, so we don’t have that problem here.

Then we’ll check if it’s a circle, if not we’ll exit.

### Polygon

Polygons are probably the most easiest. However you can only load polygons with a maximum of 8 points.

That’s pretty much everything you need!

## Repo

https://github.com/lyze237-examples/LibgdxTiledBox2DExample