1

I am making a side-scroller game. In order to prevent flickering in my game, I began using a backbuffer for smoother graphics. It fixed most of the problems, however, if I move the character for long enough, the screen starts to flicker. I read about the problem here, but it did not detail how to fix this vertical blanking interval. I understand that it's not actually "flickering", but more "tearing" as the new is painted on the old. Is there any way to avoid this "tearing"?

Thanks!

Community
  • 1
  • 1
faeophyta
  • 323
  • 5
  • 16
  • When do you redraw? Constantly in a loop, or when the user moves the character? This is purely speculation based on the fact that it only happens when you move the character for an extended amount of time, but if you're redrawing in the keypress function without any limit on frames per second, since keypress events fire pretty quickly, it could just be slowly falling more and more behind every time until the tearing finally starts. – jonhopkins Mar 25 '13 at 14:24
  • Answering my own question. This link is helpful [link](http://www.koonsolo.com/news/dewitters-gameloop/) – faeophyta Mar 25 '13 at 14:40

2 Answers2

0

I would have answered in a comment but there's too much detail for that. The following code is taken pretty much exactly from an applet in which I had to limit FPS the same way you are now (except it was on mouseMove instead of keyPressed).

private long lastDrawTime = 0;

public void keyPressed(KeyEvent e) {
    if (Calendar.getInstance().getTimeInMillis() - lastDrawTime < 20) return;
    //do whatever needs to be done before redrawing
    draw();
    lastDrawTime = Calendar.getInstance().getTimeInMillis();
}

What's happening here is that there is an instance variable lastDrawTime that stores the time that the last redraw happened. This variable is compared to the current time of the keyPressed event being fired before any drawing happens. If the difference in time is less than the allowed interval, in this case 20 milliseconds, or 50 frames per second, then the function returns and no drawing or updating is done. If enough time has passed, however, all the normal stuff is done, and the current time is stored in the variable.

jonhopkins
  • 3,844
  • 3
  • 27
  • 39
  • Thanks! This is much easier than the method that I found. – faeophyta Mar 25 '13 at 14:43
  • The article you found is actually really useful. This answer is useful for the current context of only needing to update on user input, but once you start adding other things like enemies that move independently of the player, you'll be better off using the method described in the article. – jonhopkins Mar 25 '13 at 14:44
0

You need to implement a Constant Game Speed independent of Variable FPS. This Article details how to do so.

faeophyta
  • 323
  • 5
  • 16