# How do I stop off-screen tiles of a 2D tilemap from being rendered?

I am seeing lag because I render all tiles in my map at once. How can I exclude off-screen tiles from being rendered?

My tiles are 32×32 and my player is always in the centre of the screen.

Here is my render method:

JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) obj;

for(int x = 0; x < worldWidth; x++) {
for (int y = 0; y < blocksHeight; y++) {
Object out = jsonObject.get("x"+x+"y"+y);
String f = out.toString();
int i = Integer.parseInt(f);
g.drawImage(GetImage.ReturnImage(i), x*Size.Tile, y*Size.Tile);
}
}

• Possible duplicate of How to draw only visible tiles? Oct 14 '15 at 2:40
• no his is a 3d plane mine is 2d Oct 14 '15 at 5:44
• Don't worry i managed to get it working with this: if (x > (InGame.playerX/32) - 17 && x < (InGame.playerX/32)+18 && y > (InGame.playerY/32) - 5 && y < (InGame.playerY/32)+15) { g.drawImage(GetImage.ReturnImage(i), xSize.Tile, ySize.Tile); } Oct 14 '15 at 13:16
• maybe instead of redoing the post you could have helped?? Oct 14 '15 at 22:35

One way you could do it is by testing to see if the tile is outside the screen

int screenWidth = [GET_THE_SCREEN_WIDTH];
int screenHeight = [GET_THE_SCREEN_HEIGHT];
for(int x = 0; x < worldWidth; x++) {
for (int y = 0; y < blocksHeight; y++) {
Object out = jsonObject.get("x"+x+"y"+y);
String f = out.toString();
int i = Integer.parseInt(f);
if(!x*Size.Tile>screenWidth && !(x-1)*Size.Tile < 0){
if(!y*Size.Tile>screenHeight && !(y-1)*Size.Tile < 0){
g.drawImage(GetImage.ReturnImage(i), x*Size.Tile, y*Size.Tile);
}
}
}
}


That is how I would do it. And, yes, I have tested it. It works perfectly. You will need to replace '[GET_THE_SCREEN_WIDTH]' and '[GET_THE_SCREEN_HEIGHT]' with a real variable, obviously.

Hope this has helped you