Using TiledCS
Install TiledCS
The easiest method is to create your MonoGame project then:
- Click on project & select Nuget Package Manager
- Search online for TiledCS & Install
- In the Game1.cs of your project add:
using TiledCS;
You can also get the source code from the link below, and copy the `.cs` files into the same folder as your `Game1.cs` or in a new folder within this.
Pro's
- Still active on GitHub
- Good ReadMe with examples
- Good example of drawing
Con's
- Complex draw method
- doesn't handle multiple tilesets well
- Last update 2 years +
Documentation
https://github.com/TheBoneJarmer/TiledCS?tab=readme-ov-file
Drawing a Map
You will need to create the following variables within `Game1.cs`:
TiledMap map;
Texture2D ts;
In the `LoadContent` method of `Game1.cs` you need to add the following to load in the map:
map = new TiledMap("Content/real.tmx");
var tilesets = map.GetTiledTilesets("Content/"); // DO NOT forget the / at the end
ts = Content.Load<Texture2D>(tilesets[1].Image.source.Split(".")[0]);
Finally in the `Draw` method of `Game1.cs` you need the following code to draw the map itself:
var tilesets = map.GetTiledTilesets("Content/"); // DO NOT forget the / at the end
var tileLayers = map.Layers.Where(x => x.type == TiledLayerType.TileLayer);
_spriteBatch.Begin();
foreach (var layer in tileLayers)
{
for (var y = 0; y < layer.height; y++)
{
for (var x = 0; x < layer.width; x++)
{
var index = (y * layer.width) + x; // Assuming the default render order is used which is from right to bottom
var gid = layer.data[index]; // The tileset tile index
var tileX = (x * map.TileWidth);
var tileY = (y * map.TileHeight);
// Gid 0 is used to tell there is no tile set
if (gid == 0)
{
continue;
}
// Helper method to fetch the right TieldMapTileset instance.
// This is a connection object Tiled uses for linking the correct tileset to the gid value using the firstgid property.
var mapTileset = map.GetTiledMapTileset(gid);
// Retrieve the actual tileset based on the firstgid property of the connection object we retrieved just now
var tileset = tilesets[mapTileset.firstgid];
// Use the connection object as well as the tileset to figure out the source rectangle.
var rect = map.GetSourceRect(mapTileset, tileset, gid);
// rect is not an actual rectangle, so create one for _spriteBatch to use.
Rectangle tilerec= new Rectangle(rect.x, rect.y, rect.width, rect.height);
// Render sprite at position tileX, tileY using the rect
_spriteBatch.Draw(ts, new Rectangle((int)tileX, (int)tileY, 32, 32), tilerec, Color.White);
}
}
}
_spriteBatch.End();