Currently I am creating a small game.
I created a tilemap in the tilemap-editor Tiled.
However, I am not sure how to actually display the tilemap on the screen.
I exported the tilemap into a format called “.tmj”. Which is a JSON-like format and can also be parsed as if it is a JSON-file.
I use nlohmann-json as it allows for trivial integration.
Here is the code I use to parse it:
json load_map(std::string path) {
std::ifstream file(path.c_str());
assert(file.is_open());
json data = json::parse(file);
return data;
}
// Function loads and extracts JSON data
// and stores the level as a vector of rectangles.
void load_and_extract(const std::string &path, std::vector<Rectangle> &level) {
json level_data = load_map(path);
int tile_width = level_data["tilewidth"];
int tile_height = level_data["tileheight"];
int width = level_data["layers"][0]["width"];
int height = level_data["layers"][0]["height"];
auto coords = level_data["layers"][0]["data"];
/*
for (size_t i = 0; i < coords.size(); ++i) {
int tile_id = coords[i];
if (tile_id > 0) {
int x = (i % width) * tile_width;
int y = (i / width) * tile_height;
level.push_back({(float)x, (float)y, (float)tile_width, (float)tile_height});
}
}
*/
}
My question now is:
How can I actually use the data provided in the generated .tmj-file?
As it seems, the tiles I used for the tilemap creation are identified by a unique id.
Here a small snippet of the file:
"layers":[
{
"data":[391, 391, 391, 391, 391, ...
I’m not sure about the whole procedure.
Do I have to load the .png tilesheet? As it seems, the .tmj file “knows” where the .tmx is located and the .tmx “knows” where the .png is located.
Any help is appreciated.