I'm in the process of trying to get familiar with making games in Java, using the Swing library.
Coding my Snake game however, I've got to a point where the game is flickering/ghosting and I haven't a clue why.
An example of the flickering can be seen on this short youtube video: http://www.youtube.com/watch?v=QP1IcZ5TRoY
I dread to post too much code here as it won't help anyone, but for glancers, I'll post some facts.
- Painting on a JComponent
- I do call super.paintComponent(g) at the start of my overrriden paintComponent method
- I've set setDoubleBuffered(boolean) to true.
- Although unsure of its necessity, I've invoked createBufferStrategy(2) on my JFrame
- My "game loop" is based on a swing.Timer calling repaint every 17ms, but tried, 30fps
- Snake piece moves at 25 pixel paces (or relative to world size).
This is how I draw each tile:
for (int i = 0; i < gamePieces.length; i++) {
int x = i % ROW_COL_SIZE;
int y = i / ROW_COL_SIZE;
if (gamePieces[i].equals(Tile.EMPTY)) {
continue;
} else {
final SnakeGraphics gfx = gamePieces[i].getGraphic();
gfx.draw(g2d, x, y, direction);
}
}
This is what is called on repaint:
public void render(Graphics2D g2d) {
Direction dir = keyboard.getDirection();
snake.setDirection(dir);
snake.move();
gameWorld.draw(g2d, dir);
}
and finally, how the snake moves:
public boolean move() {
Point snakeHead = snake.getFirst();
int x = snakeHead.x;
int y = snakeHead.y;
boolean success = validateStep(snakeHead); //boundary control + move
if (success) {
gameWorld.setTile(x, y, Tile.EMPTY);
gameWorld.setTile(snakeHead.x, snakeHead.y, Tile.SNAKE_HEAD);
}
return success;
}
where gameWorld has all the tile information, i.e. what tiles get drawn and where, and Snake is just current position of the head thus far.
Apologies for the code-drop, but its all that I can determine to be relevant.