03. Adding Collision


The Tiled plugin includes the TileShapeCollection  class – a standard object for efficient tile-based collision

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

Automatic vs. Code-Based TileShapeCollection Creation

TileShapeCollections can be created in one of two ways:

  1. Automatically by adding shapes to tiles in the Tiled program
  2. In code by creating collision based on tile names or properties

We will cover approach #1 (adding shapes to tiles) first since it is the simplest to get working. Additional methods will be discussed at the end of this tutorial.

Adding Shapes to Tiles

To add shapes to tiles:

  1. Open Level1Tmx.tmx in Tiled
  2. Select the tileset (tsx) tab in Tiled

    If you do not see a .tsx tab, click the edit button on the tileset in your level

  3. Click the Tile Collision Editor button

  4. Select a tile which should have collision, such as a wall tile

  5. Zoom the Tile Collision Editor to make accurate edits easier

  6. Select the rectangle tool

  7. Select the option to snap to pixels – this is important because we want to make sure the collision is accurately placed at the edges of the tiles

  8. Click+drag to set a rectangle around the tile
  9. If necessary, adjustments can be made to the rectangle using the Select Objects tool

Make sure you use this tile in your map. If not, paint on your level using the tile with collision.

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

Viewing the TileShapeCollection

Now that we’ve added shapes to our tiles and used them in our tile map, our game automatically creates a TileShapeCollection. To view it we need to make it visible. To do this, open GameScreen.cs  in Visual Studio and add the following code to CustomInitialize :

Run the game and you should see the rectangles for each of the wall tiles:

Collision can be turned on during debug, but code for making collisions visible should probably be turned off before releasing your game.

Creating TileShapeCollections in Code

As mentioned earlier, TileShapeCollection instances can also be created in code. For more information on creating collision in code from Tiles, see these links: