Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "TileMap.hpp"
- TileMap::TileMap()
- {
- load();
- }
- TileMap::~TileMap()
- {
- }
- void TileMap::load()
- {
- tson::Tileson t;
- tson::Map map = t.parse(fs::path("Res/ultimate_test.json"));
- tson::Layer* tileLayer = map.getLayer("Main Layer"); //This is a Tile Layer.
- tson::Tileset* tileset = map.getTileset("demo-tileset"); //You will also need the tileset used
- //by the tile map to make sense of everything
- int firstId = tileset->getFirstgid(); //First tile id of the tileset
- int columns = tileset->getColumns(); //For the demo map it is 8.
- int lastId = (tileset->getFirstgid() + tileset->getTileCount()) - 1;
- //Example from a Tile Layer
- //I know for a fact that this is a Tile Layer, but you can check it this way to be sure.
- if (tileLayer->getType() == tson::Layer::Type::TileLayer)
- {
- //pos = position in tile units
- for (auto& [pos, tile] : tileLayer->getTileData()) //Loops through absolutely all existing tiles
- {
- fs::path imagePath;
- std::string pathStr;
- //With this, I know that it's related to the tileset above (though I only have one tileset)
- if (tile->getId() >= firstId && tile->getId() <= lastId)
- {
- imagePath = tileset->getImagePath();
- pathStr = imagePath.u8string();
- }
- //Get position in pixel units
- tson::Vector2i position = { std::get<0>(pos) * map.getTileSize().x,std::get<1>(pos) * map.getTileSize().y };
- int tileId = tile->getId();
- //The ID can be used to calculate offset on its related tileset image.
- int offsetX = (tileId % columns) * map.getTileSize().x;
- int offsetY = (tileId / 8) * map.getTileSize().y;
- //Now you can use your library of choice to load the image (like SFML), then set the offset
- //to get the right image representation of the tile.
- mTexture.loadFromFile(pathStr);
- }
- mSprite.setTexture(mTexture);
- }
- }
- void TileMap::render(sf::RenderTarget& target)
- {
- target.draw(mSprite);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement