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:
- Automatically by adding shapes to tiles in the Tiled program
- 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:
- 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
- Click the Tile Collision Editor button
- Select a tile which should have collision, such as a wall tile
- Zoom the Tile Collision Editor to make accurate edits easier
- Select the rectangle tool
- 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
- Click+drag to set a rectangle around the tile
- 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 :
Camera.Main.X = Camera.Main.OrthogonalWidth / 2.0f;
Camera.Main.Y = -1 * Camera.Main.OrthogonalHeight / 2.0f;
// Add the code to make all shape collections in the level visible:
foreach(var tileShapeCollection in Level1.Collisions)
tileShapeCollection.Visible = true;
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: