我正在使用 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
提前致谢...
我在网上找到了解决方案,并稍微修改了一下。它工作完美!只需将此函数添加到您的类中即可:
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();
}
}
然后在你的render
功能:
int fps = 30; //limit to 30 fps
//int fps = 0;//without any limits
@Override
public void render() {
//draw something you need
sleep(fps);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)