Hi guys,
So i’m trying to implement a really big, randomly generated tile map which supports negative coordinates in my game.
I’ve decided to use a hashmap for this.
private HashMap<Vector2, TiledMapTileLayer.Cell> worldHashMap;
The Vector stores the x and y coordinate of the tile, and the cell stores the tile.
This all works fine.
Drawing the world also works well
public void drawWorld(Batch batch){
batch.begin();
for(Map.Entry<Vector2, TiledMapTileLayer.Cell> entry: worldHashMap.entrySet()){
Vector2 v2World = entry.getKey();
TiledMapTileLayer.Cell cellWorld = entry.getValue();
batch.draw(cellWorld.getTile().getTextureRegion(), v2World.x * cellWorld.getTile().getTextureRegion().getRegionWidth(), v2World.y * cellWorld.getTile().getTextureRegion().getRegionHeight());
}
batch.end();
}
The problem is that the bigger the world gets, the more tiles it’s trying to render at once. With only 2500 Tiled this works fine, but with 250000 I’m down to 5 FPS. I think the problem is it’s also trying to render all the tiles that aren’t on screen.
So I’ve been trying to get it to only draw the tiles which are visible.
This is the best code I’ve come up with
public void drawWorld(Batch batch){
batch.begin();
for(Map.Entry<Vector2, TiledMapTileLayer.Cell> entry: worldHashMap.entrySet()){
Vector2 v2World = entry.getKey();
TiledMapTileLayer.Cell cellWorld = entry.getValue();
//Check if the bottom left corner of the tile is to the right of the left most part of the screen plus an additional length of the tile & if it's past the right edge of the screen
if((v2World.x > camera.position.x - camera.viewportWidth / 2 - cellWorld.getTile().getTextureRegion().getRegionWidth()) && (v2World.x < camera.position.x + camera.viewportWidth / 2)) {
//Same for top and bottom of the screen.
if (v2World.y > camera.position.y - camera.viewportHeight / 2 - cellWorld.getTile().getTextureRegion().getRegionHeight() && (v2World.y < camera.position.y + camera.viewportHeight / 2)) {
batch.draw(cellWorld.getTile().getTextureRegion(), v2World.x * cellWorld.getTile().getTextureRegion().getRegionWidth(), v2World.y * cellWorld.getTile().getTextureRegion().getRegionHeight());
}
}
}
batch.end();
}
First of all, the code doesn’t really work. When I spawn my player at (0|0) of the world (the camera follows the player), everything around him is rendered properly. But as soon as I move a bit in any direction, the tiles stop rendering.
The second problem is that as soon as I increase the amount of tiles in the world the FPS drops dramaticlly, even though (i think) the tiles off screen arent’t rendered.
I’m assuming this has to to with the fact that I’m calling the drawWorld 60 times a second, and each times it’s call it iterates through 250000 entries in my Hashmap, which is way too much.
Can someone tell me what I’m doing wrong or maybe have an idea of how I can solve this issue in a better/more elegant way?