I have my game which, on every render loop, loops through all the blocks in my map (128×128) which as you can probably tell, causes a lot of lag. When I first made it, I had to make it render only the blocks on the screen, or it would crash instantly. Now I only render the blocks on the screen, but still loop through all the blocks to see if they are on the screen, which makes my fps about 2.
for (int y = 0; y < 128; y++) {
for (int x = 0; x < 128; x++) {
Block b = LevelGen.getBlockAt(x, y);
if (Forgotten.isInsideGameWindow(x * 30, y * 30)) {
arg1.drawImage(b.getTexture(), x * 30, y * 30);
}
}
}
Is there a way to make it so doesn’t loop through all of them?
Figure out the size of your display window, and only iterate blocks that are within it.
You may also want to figure out which area(s) of the canvas actually want to be drawn, and instead keep a “dirty rectangle” list of areas to be redrawn. Whenever a tile changes, or a sprite/particle/whatever passes through its space, add that tile to the rectangle. Even if you just use a single dirty rectangle that enlarges to encompass all updates during a frame, if your game doesn’t actually have “stuff happening” at all points on the display at all times, your frame rate will be higher on average (but suffer from large-scale effects)
expanding upon that:
Then use the dirty rectangle in place of
displayWindowfor normal draws, and you can testif (null == getDirtyRectangle ()) return;to skip drawing at all if nothing’s changed.