03. Adding Collision


The Tiled plugin includes the TileShapeCollection  class which simplifies creation of collision from tile maps. TileShapeCollection  also includes extremely efficient collision methods.

This walk-through shows how to create and use the TileShapeCollection  class in a game to perform common collision logic.

Setting Tile Names

Tile map collision is created by identifying which tiles should have collision. Tiles are identified at runtime by their Name. Therefore, collidable tiles must have a Name property.

Note that Name is a special variable used by the tool to connect tiles in the tileset to tiles in the tile map at runtime. Furthermore, Name must be unique in a tileset. Using the same name for multiple tiles in a tileset will result in a runtime exception.

To set the name of a tile:

  1. In Tiled, click on a tile in the Tileset window

  2. If the tile property window isn’t visible, right-click on the tile and select “Tile Properties…”

    1. Note that if the “Tile Properties…” option doesn’t appear, you need to go to edit mode for the tileset (the wrench button).

  3. Click the add button to add a property

  4. Enter “Name” and click “OK”

  5. Enter a value of “Wall” for the new Name property

We will also place some wall tiles on the tile map so we can test collision in our game:

Don’t forget to save the tile map after making these changes.

Creating a TileShapeCollection

Next we’ll create a TileShapeCollection  in our GameScreen. Tile-based games will typically have at least one TileShapeCollection  instance in the GameScreen. Games requiring different types of collision behavior (such as solid walls and damaging spikes) will need multiple TileShapeCollection  instances.

To create a TileShapeCollection :

  1. Open the GameScreen.cs  file in Visual Studio
  2. Add the following using statement to the GameScreen.cs  file:
  3. Add the following to the GameScreen  class:
  4. Modify the CustomInitialize  method to add collision from all tiles with the name "Wall" :
  5. Run the game and you should see the rectangles for each of the wall tiles:

TileShapeCollection  instances create visible rectangles by default. The Visible  property can be set to false to hide the rectangles. Setting the Visible  property to false  before calling AddCollisionFrom  makes initialization run faster:

Cleaning up Collision

Since our custom code creates the TileShapeCollection  instance, our custom code must also remove it when the screen is destroyed.

To do this, modify the CustomDestroy  method as follows: