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

The first approach (adding shapes to tiles) is the simplest approach as it requires no code. Additional methods will be discussed at the end of this tutorial.

Adding Shapes to Tiles

To add shapes to tiles:

  1. 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

  2. Click the Tile Collision Editor button

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

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

  5. Select the rectangle tool

  6. 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

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

Make sure you use this tile in your map.

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: