使用Thread.sleep()限制Libgdx游戏中的FPS不起作用

我正在为libgdx开发一款针对android的小游戏,并希望将fps限制为30以节省电池。 问题是它不起作用。 fps从60下降到56。

以下是代码的一部分:(它位于渲染部分的末尾)

System.out.print("\nFPS: " + Gdx.graphics.getFramesPerSecond() + "\n"); if(Gdx.graphics.getDeltaTime() < 1f/30f) { System.out.print("DeltaTime: " + Gdx.graphics.getDeltaTime() + " s\n"); float sleep = (1f/30f-Gdx.graphics.getDeltaTime())*1000; System.out.print("sleep: " + sleep + " ms\n"); try { Thread.sleep((long) sleep); } catch (InterruptedException e) { System.out.print("Error..."); e.printStackTrace(); } } 

这是输出:

 FPS: 56 DeltaTime: 0.014401722 s sleep: 18.931612 ms FPS: 56 DeltaTime: 0.023999143 s sleep: 9.334191 ms FPS: 56 DeltaTime: 0.010117603 s sleep: 23.215733 ms 

提前致谢…

使用可能会使用此

 Thread.sleep((long)(1000/30-Gdx.graphics.getDeltaTime())); 

将值30更改为您想要的FPS。

我在互联网上找到了一个解决方案并对其进行了一些修改。 它完美无瑕! 只需将此function添加到您的class级:

 private long diff, start = System.currentTimeMillis(); public void sleep(int fps) { if(fps>0){ diff = System.currentTimeMillis() - start; long targetDelay = 1000/fps; if (diff < targetDelay) { try{ Thread.sleep(targetDelay - diff); } catch (InterruptedException e) {} } start = System.currentTimeMillis(); } } 

然后在你的renderfunction中:

 int fps = 30; //limit to 30 fps //int fps = 0;//without any limits @Override public void render() { //draw something you need sleep(fps); } 
 import com.badlogic.gdx.utils.TimeUtils; public class FPSLimiter { private long previousTime = TimeUtils.nanoTime(); private long currentTime = TimeUtils.nanoTime(); private long deltaTime = 0; private float fps; public FPSLimiter(float fps) { this.fps = fps; } public void delay() { currentTime = TimeUtils.nanoTime(); deltaTime += currentTime - previousTime; while (deltaTime < 1000000000 / fps) { previousTime = currentTime; long diff = (long) (1000000000 / fps - deltaTime); if (diff / 1000000 > 1) { try { Thread.currentThread().sleep(diff / 1000000 - 1); } catch (InterruptedException e) { e.printStackTrace(); } } currentTime = TimeUtils.nanoTime(); deltaTime += currentTime - previousTime; previousTime = currentTime; } deltaTime -= 1000000000 / fps; } } 

您可以将Libgdx的“非连续渲染”视为降低Android上帧速率的替代方法。 因为它的应用程序的UI线程将陷入困境,因此您的应用程序可能响应性较差(虽然睡眠时间为30秒并不是那么长)。

根据您的游戏,非连续渲染支持可能会让您进一步降低帧速率(任何时候图形没有变化且没有预期输入,您不需要绘制新帧)。