2
\$\begingroup\$

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();
Object obj = parser.parse(new FileReader("assets/maps/"+map+".json"));
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);
    }
}
\$\endgroup\$
  • \$\begingroup\$ Possible duplicate of How to draw only visible tiles? \$\endgroup\$ – Steven Oct 14 '15 at 2:40
  • \$\begingroup\$ no his is a 3d plane mine is 2d \$\endgroup\$ – Hamish Oct 14 '15 at 5:44
  • \$\begingroup\$ 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); } \$\endgroup\$ – Hamish Oct 14 '15 at 13:16
  • \$\begingroup\$ maybe instead of redoing the post you could have helped?? \$\endgroup\$ – Hamish Oct 14 '15 at 22:35
1
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.