Advertisement
Guest User

Untitled

a guest
Sep 21st, 2019
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. #include "TileMap.hpp"
  2.  
  3. TileMap::TileMap()
  4. {
  5.     load();
  6. }
  7.  
  8. TileMap::~TileMap()
  9. {
  10. }
  11.  
  12. void TileMap::load()
  13. {
  14.     tson::Tileson t;
  15.     tson::Map map = t.parse(fs::path("Res/ultimate_test.json"));
  16.  
  17.     tson::Layer* tileLayer = map.getLayer("Main Layer"); //This is a Tile Layer.
  18.     tson::Tileset* tileset = map.getTileset("demo-tileset"); //You will also need the tileset used
  19.                                                                     //by the tile map to make sense of everything
  20.  
  21.     int firstId = tileset->getFirstgid(); //First tile id of the tileset
  22.     int columns = tileset->getColumns(); //For the demo map it is 8.
  23.     int lastId = (tileset->getFirstgid() + tileset->getTileCount()) - 1;
  24.  
  25.     //Example from a Tile Layer
  26.     //I know for a fact that this is a Tile Layer, but you can check it this way to be sure.
  27.     if (tileLayer->getType() == tson::Layer::Type::TileLayer)
  28.     {
  29.         //pos = position in tile units
  30.         for (auto& [pos, tile] : tileLayer->getTileData()) //Loops through absolutely all existing tiles
  31.         {
  32.             fs::path imagePath;
  33.             std::string pathStr;
  34.             //With this, I know that it's related to the tileset above (though I only have one tileset)
  35.             if (tile->getId() >= firstId && tile->getId() <= lastId)
  36.             {
  37.                 imagePath = tileset->getImagePath();
  38.                 pathStr = imagePath.u8string();
  39.             }
  40.  
  41.             //Get position in pixel units
  42.             tson::Vector2i position = { std::get<0>(pos) * map.getTileSize().x,std::get<1>(pos) * map.getTileSize().y };
  43.             int tileId = tile->getId();
  44.             //The ID can be used to calculate offset on its related tileset image.
  45.             int offsetX = (tileId % columns) * map.getTileSize().x;
  46.             int offsetY = (tileId / 8) * map.getTileSize().y;
  47.  
  48.             //Now you can use your library of choice to load the image (like SFML), then set the offset
  49.             //to get the right image representation of the tile.
  50.  
  51.             mTexture.loadFromFile(pathStr);
  52.         }
  53.  
  54.         mSprite.setTexture(mTexture);
  55.     }
  56. }
  57.  
  58. void TileMap::render(sf::RenderTarget& target)
  59. {
  60.     target.draw(mSprite);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement