I created a 2D game in java and am trying to get it to 60 fps with a resolution of 1920x1080 pixels. My game logic is performing fine in less than 1 millisecond. But the drawing takes up to over 10 milliseconds. This might be sufficient on my rather strong desktop (intel i5-4670K @ 3.40 Ghz), but on my laptop (intel i5-6300HQ @2.30 Ghz) the game is already slowing down quite a bit. The drawing is separated into two main steps:
draw every component of the game onto a BufferedImage
draw the BufferedImage in my extended JPanel class
The corresponding code is this:
@Override
public void run() {
init();
long startTime;
long elapsedTime;
long waitTime;
while(running) {
startTime = System.nanoTime();
update();
long updateTime = (System.nanoTime() - startTime) / 1000000;
draw();
long drawTime = (System.nanoTime() - startTime) / 1000000;
drawToScreen();
long drawscreenTime = (System.nanoTime() - startTime) / 1000000;
elapsedTime = System.nanoTime() - startTime;
waitTime = targetTime - elapsedTime / 1000000;
if(waitTime < 0) {
waitTime = 0;
}
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void init() {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice device = env.getDefaultScreenDevice();
GraphicsConfiguration config = device.getDefaultConfiguration();
image = config.createCompatibleImage(1920, 1080, Transparency.TRANSLUCENT);
g2d = (Graphics2D) image.getGraphics();
running = true;
gsm = new GameStateManager(this);
}
public void update() {
gsm.update();
Keys.update();
}
public void draw() {
gsm.draw(g2d);
}
public void drawToScreen() {
Graphics g = getGraphics();
g.drawImage(image, 0, startDrawY, scaledWidth, scaledHeight, null);
g.dispose();
}
Both the draw and drawToScreen methods take up to 5 milliseconds. inside the draw method, the slowest parts are drawing the background image (1920x1080 image) and drawing the level (consisting of several 135x135 images), which both take a few milliseconds.
Now i have two questions: Is this draw-speed normal for large images like that? And if not what might I be doing wrong here or how can I improve the drawing-performance?