Tag: sharpdl

How to load a map from Tiled Map Editor and render it with SDL2

I recently created a library named SharpTiles that is heavily based on Nick Gravelyn’s TiledLib. Both libraries will allow developers to load maps from Tiled Map Editor. However, TiledLib is based around XNA while SharpTiles is based around SharpDL (an XNA-like game framework for SDL2). I will discuss more about SharpDL in another post, but you can refer to the simple code in this post to learn how to render a map with a small subset of the library.

Load a Map

  • Window is a SharpDL object that represents a SDL_Window
  • Renderer is a SharpDL object that represents a SDL_Renderer
  • TiledMap is the main object that you will use to load a map file
// create an SDL window at position 100,100 with size 640x480
Window window = new Window("Example 1", 100, 100, 640, 480, Window.WindowFlags.Shown)

// create an SDL rendering context based on the window above
Renderer renderer = new Renderer(Renderer.RendererFlags.RendererAccelerated);

// load and create map to be displayed in the passed Renderer
TiledMap map = new TiledMap("Maps/Map1.tmx", Renderer);

Draw a Map

You can draw a map by looping through all TileLayers (layers which containd textured tiles) and all Tiles within the layers. Make sure to check if the tile is empty before drawing it. Tiled Map Editor will create empty tiles in spots that contain no textured tiles within the layer.

  • Texture is the tileset that contains the tile’s texture
  • Position.X is the X position of the tile to draw
  • Position.Y is the Y position of the tile to draw
  • SourceTextureBounds is a rectangle that indicates where in the tileset the tile’s actual texture is contained
foreach (TileLayer tileLayer in map.TileLayers)
    foreach (Tile tile in tileLayer.Tiles)
        if (!tile.IsEmpty)
            Renderer.RenderTexture(tile.Texture, (int)tile.Position.X, (int)tile.Position.Y, tile.SourceTextureBounds);
Read more