I am programming a platformer game in Java. Everything works fine and there are no bigger problems, except the flickering on the screen when the Canvas
is updated.
I'll roughly explain how my game "engine" works: In my main method, I have a Loop, that is repeating itself 30 times a second:
while (play) {
Date delay_time = new Date();
delay_time.setTime(delay_time.getTime() + (int) (1000*(1.0/FPS)));
// Here is all the game stuff, like the motion of the player,
// function calling, etc.
Graphics g = can.getGraphics();
can.update(g);
while(new Date().before(delay_time)) {
}
}
My FPS variable is a static final int
that is currently set to 30.
So i am updating my Canvas 30 time a second.
Play is a boolean, which controls if the game is still playing, or the player died.
Can
is an instance of my class MyCanvas.java
.
The Code of the paint() method looks like so:
if (Main.play) {
//NOW
//Draw the now Level Caption
//SIZE: 240
g2.setFont(new Font("Bank Gothic", Font.PLAIN, 240));
g2.setColor(new Color(Math.abs(bg.getRed() - 30), Math.abs(bg.getGreen() - 30), Math.abs(bg.getBlue() - 30)));
g2.drawString("LEVEL " + Main.lvl, 80, 80 + 300 - Main.groundY);
//Draw the ground
g2.setColor(haba);
g2.fillRect(0, Main.screenSize.height - Main.groundY, Main.screenSize.width, Main.groundY);
//Draw the level
g2.setColor(haba);
for (int i = 0; i < Main.LVLWIDTH; i++) {
for (int j = 0; j < Main.LVLHEIGHT; j++) {
if (Main.level[i][j] == '1') {
g2.fillRect(i*(Main.BLOCK_X), (j - Main.LVLHEIGHT)*(Main.BLOCK_Y) + Main.screenSize.height - Main.groundY, Main.BLOCK_X, Main.BLOCK_Y);
}
}
//More drawing stuff...
}
So, as you can see, I am updating quite a lot - 30 times a second. This leads to the problem that my game (which is playing in fullscreen mode BTW) flickers all the time. How do solve that problem? Is a Bufferstrategy the right way? And if yes, how should I do it? Can you please explain the Bufferstartegy or provide links that have great tutorials or explanations, which or not to technical and non-beginner friendly? That would be great.
The BufferStrategy class solved my problem. Here is a good link to it, with a well made example of how to use it:
http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferStrategy.html