Skip to content

TiledMaps

Modar Nasser edited this page Sep 13, 2020 · 11 revisions

TiledMap is part of the tilemapping module

TiledMap are one of the most common thing we can find in games.

NasNas supports TiledMaps rendering from Tiled tmx files exported in csv format.

Almost all Tiled features are implemented, except :

  • Isometric and hexagonal maps
  • Layers groups
  • Image layers
  • Tile objects in objectsgroups
  • Tile collisions

These features will be implemented sometime in the future.

Loading and drawing a tiled map is effortless in NasNas, let's see an example :

First of all, add a TiledMap member variable to the Game class header.

Game::Game(){
    auto* scene = createScene("main");

    // let's suppose we want to load the level.tmx tiled map.
    // it has 2 tile layers named bg and front, and an object layer named coins
    this->tiled_map.loadFromFile("assets/level.tmx");
    
// iterate over point objects in the coin object layer
    for (auto& object : this->tiled_map.getObjectLayer("coins").allPoints()) {
        // do something with the objects
    }
    
    // adding tile layers to the scene
    scene->getDefaultLayer()->add(this->tiled_map.getTileLayer("bg"));
    scene->getDefaultLayer()->add(this->tiled_map.getTileLayer("front"));
    // we can also add an object layer to the Scene
    // the objects will be drawn like how they appear in Tiled map editor
    scene->getDefaultLayer()->add(this->tiled_map.getObjectLayer("coins"));

    auto* camera = createCamera("main");
    camera->lookAt(scene);
    //  we can set camera limits to be the tiled map bounds
    camera->setLimitsRect({{0, 0}, sf::Vector2i(tiled_map.getSize())});

}

Game::update() {
    this->tiled_map.update();
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
        getCamera("main")->move(1, 0);
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
        getCamera("main")->move(0, 1);
    // if (...) ... etc
}

This example will load a Tiled map, draw it on the screen and update its animated tiles. Press the arrow keys to move the Camera.

Thing you can do with the loaded tiled map :

  • Get properties (from map, layer, object, tile or tileset)
  • Get specific tile data
  • Get tilesets data
  • Get objects shapes

The tilemapping module is quite big, please check its documentation for more details