I’m trying to create a tilemap in one of my games and I would like to split the tilemap up into grids. By making grids containing a fixed amount of tiles, I only need to render the portion(s) of the tilemap that’s visible inside the camera (i.e, the grid(s) that’s currently inside the camera viewport).
The code I’m having at the moment:
struct STileGrid { std::vector<STile*> TileList; // Upper left corner of the grid CVector2D StartPosition; // Lower right corner of the grid CVector2D EndPosition; }; ////////////////////////////////////////////////////////////////////////// // Hardcoded during testing const CVector2D WindowSize = CVector2D(1280.0f, 720.0f); // Number of horizontal/vertical tiles in the map const CVector2D MapSize = CVector2D(60.0f, 36.0f); const CVector2D TileSize = CVector2D(64.0f, 64.0f); // (20.0f, 12.0f) in this case (number of horizontal/vertical tiles in each grid) const CVector2D GridSize = CVector2D(ceil(WindowSize.x / TileSize.x), ceil(WindowSize.y / TileSize.y)); // 3 horizontal, 3 vertical in this case const unsigned int NumHorizontalGrids = (int)ceil(MapSize.x / GridSize.x); const unsigned int NumVerticalGrids = (int)ceil(MapSize.y / GridSize.y); ////////////////////////////////////////////////////////////////////////// std::vector<STileGrid*> TileGridList; m_TileGridList.resize(NumHorizontalGrids * NumVerticalGrids); CreateTileGridList(); for(unsigned int i = 0; i < m_pTmxMap->GetNumTileLayers(); ++i) { const CTmxTileLayer* pTmxTileLayer = m_pTmxMap->GetTileLayer(i); if(!pTmxTileLayer->GetIsVisible()) continue; const unsigned int LayerWidth = (int)MapSize.x; const unsigned int LayerHeight = (int)MapSize.y; for(unsigned int y = 0; y < LayerHeight; ++y) { for(unsigned int x = 0; x < LayerWidth; ++x) { const CTmxTile& rTmxTile = pTmxTileLayer->GetTile(x, y); if(rTmxTile.GetIsEmpty()) continue; STile* pTile = new STile; // Upper left corner of the tile pTile->Position = CVector2D(TileSize.x * x, TileSize.y * y); pTile->ID = rTmxTile.GetID(); // Setting some other tile data // Place the tile inside the first grid TileGridList[0]->TileList.push_back(pTile); } } }
This code works fine so far. However, I would like to place each tile in the correct grid. At the moment, I’m doing TileGridList[0]->TileList.push_back(pTile);
to place each tile inside the first grid, but instead of placing each tile in the first grid, I would like to, in some way, calculate which grid each tile should be placed inside, based on the grid’s- and the tile’s position.
The following image shows what I would like to achieve:
The red squares symbolizes the grids with some example tiles placed inside.
How can I, in each iteration of the x
and y
for loop, calculate an index into the tilegrid list which tells which grid to place each tile in?