In my 'Terraria' based game I am having lag issues. The cause of the lag is as follows:
- Every update loop through all the tiles in the world:
- If the rectangle that was passed as an arg intersects with the current tiles rectangle return true. If not go to the next tile.
- If the rectangle that was passed as an arg doesn't intersect with any of the tiles rectangles then return false.
My solution is to only check collisions for the tiles that are on the screen. At the moment my code renders all of the tiles regardless of the position. I know that this is a very lag-filled approach and I have no idea at all what the maths is to only get the tiles the player can see. If it helps the world is stored in a hash map that is initialised like this:
public Map<Integer, Tile> world = new HashMap<Integer, Tile>();
// numeric id = key , tile = value
I have tried looping through the tiles in 2 ways:
public boolean checkCollision(Rectangle argRect)
{
for(int i = 0; i < world.size(); i++){
Tile tile = world.get(i);
Rectangle tileRect = new Rectangle(tile.rect);
if(tileRect.intersects(argRect)){
return true;}
}
return false;
}
And:
public boolean checkCollision(Rectangle argRect)
{
for (Entry<Integer, Tile> entry : world.entrySet()) {
Object key = entry.getKey();
Tile tile = world.get(key);
Rectangle tileRect = new Rectangle(tile.rect);
if(tileRect.intersects(argRect)){return true;}
}
return false;
}
Could I pass the players position to this method and have it only loop through tiles in the area? Would this approach have to loop through the tiles to see which ones are in the area?