I'm developing a 2D tile based game in JavaFx in college, I already have the sprites, animations, audio, menu ..., but I found a huge problem in rendering the map. On a 4GB notebook, Intel graphics card, Core i5, where any 2D Steam game works well at 60 FPS, my game runs from 27 to 31 FPS. I noticed that the precarious part is rendering the map, but I do not know why it's so slow. Here is the map rendering code:
// Clear Layers
this.getLayer1GC().clearRect(0, 0, this.getLayer1GC().getCanvas().getWidth(),
this.getLayer1GC().getCanvas().getHeight());
this.getLayer2GC().clearRect(0, 0, this.getLayer2GC().getCanvas().getWidth(),
this.getLayer2GC().getCanvas().getHeight());
int index = 0;
int tileSize = 64 * Engine.SCALE; // 128x128
int startCol = Math.max(0, (int) (Engine.camera.xView / tileSize));
int endCol = Math.min(this.width,
(int) ((Engine.camera.xView + Engine.camera.wView) / tileSize) + 1);
int startRow = Math.max(0, (int) (Engine.camera.yView / tileSize));
int endRow = Math.min(this.height,
(int) ((Engine.camera.yView + Engine.camera.hView) / tileSize) + 1);
int tileX, tileY, indexLayer1, indexLayer2;
for (int c = startCol; c < endCol; c++) {
for (int r = startRow; r < endRow; r++) {
// Tile Index
index = this.tileManager.getTileIndex(c, r, this.width);
// Tile Coordinates
tileX = (int) (c * tileSize - Engine.camera.xView);
tileY = (int) (r * tileSize - Engine.camera.yView);
// Cache Tileset Images
indexLayer1 = this.layer1.tileArray[index];
indexLayer2 = this.layer2.tileArray[index];
// Layer 1
if (indexLayer1 > 0) {
this.getLayer1GC().drawImage(this.mapTilset.tileImages[indexLayer1], 0, 0,
tileSize, tileSize, tileX, tileY, tileSize, tileSize);
}
// Layer 2
if (indexLayer2 > 0) {
this.getLayer2GC().drawImage(this.mapTilset.tileImages[indexLayer2], 0, 0,
tileSize, tileSize, tileX, tileY, tileSize, tileSize);
}
}
}