我一直在互联网上寻找好几个小时,试图找到一个好的方法来重新粉刷,等到屏幕刷新后再继续使用代码。
如果我的显示器每秒更新60次,我不希望油漆代码每秒运行10000次。我已创建此代码以尝试解决此问题:
static int TICKS_PER_SECOND = 20;
static double SKIP_TICKS = 1000 / TICKS_PER_SECOND;
static int MAX_FRAMESKIP = 10;
static int FRAMES_PER_SECOND = 60;
static double SKIP_FRAMES = 1000 / FRAMES_PER_SECOND;
static int currentFPS;
static double interpolation;
//创建扩展JPanel并创建JFrame的主类
long sleepTime = 0;
long next_game_tick = System.currentTimeMillis();
long lastTick = System.currentTimeMillis();
while(processGame){
short loops = 0;
while(System.currentTimeMillis() > next_game_tick
&& loops < MAX_FRAMESKIP){
gameLogic();
next_game_tick += SKIP_TICKS;
loops++;
}
interpolation = (double) ((System.currentTimeMillis() - next_game_tick + SKIP_TICKS) / SKIP_TICKS);
game.repaint();
sleepTime = lastTick - System.currentTimeMillis();
lastTick += SKIP_FRAMES;
try{
if(sleepTime > 1){
Thread.sleep(sleepTime);
System.out.println("Sleeping for " + sleepTime);
}else{
Thread.sleep(1);
System.out.println("Running behind with " + sleepTime);
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
然而,这段代码在逻辑上不能正确地等待屏幕更新。有没有办法用waitForScreenUpdate()之类的东西来改变Thread.sleep()?