Using TiledLib

From TRCCompSci - AQA Computer Science
Revision as of 10:58, 14 February 2024 by Admin (talk | contribs) (Drawing a Map)
Jump to: navigation, search

Install TiledLib

The easiest method is to create your MonoGame project then:

  1. Click on project & select Nuget Package Manager
  2. Search online for TiledLib & Install
  3. In the Game1.cs of your project add:
    using TiledLib;
    

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

  • Last update less than a year ago
  • Available as a NuGet package
  • Example of how to draw

Con's

  • Poor readme with little information on how to use

Documentation

https://github.com/Ragath/TiledLib.Net?tab=readme-ov-file

Drawing a Map

You will need to create the following variables within `Game1.cs`:

        Map map;
        Texture2D ts;

You will then need to load these in, so add this code to the LoadContent method of the `Game1.cs`:

            string filename = "Content/real.tmx";
            var stream = File.OpenRead(filename);
            map = Map.FromStream(stream, ts => File.OpenRead(Path.Combine(Path.GetDirectoryName(filename), ts.Source)));
            ts = Content.Load<Texture2D>(map.Tilesets[0].ImagePath.Split(".")[0]);

Finally in the Draw method of `Game1.cs` add the following code:

            foreach (var layer in map.Layers.OfType<TileLayer>())
            {
                for (int y = 0, i = 0; y < layer.Height; y++)
                    for (int x = 0; x < layer.Width; x++, i++)
                    {
                        var gid = layer.Data[i];
                        if (gid == 0)
                            continue;
                        else
                        {
                            var tileset = map.Tilesets.Single(ts => gid >= ts.FirstGid && ts.FirstGid + ts.TileCount > gid);
                            var tile = tileset[gid];

                            Rectangle tilesetRec = new Rectangle(tile.Left, tile.Top, 32, 32);

                            _spriteBatch.Draw(ts, new Rectangle((int)x*32, (int)y*32, 32, 32), tilesetRec, Color.White);
                        }
                    }
            }