我正在使用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
提前感谢...
答案 0 :(得分:9)
我在互联网上找到了一个解决方案并对其进行了一些修改。它完美无缺!只需将此功能添加到您的班级:
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);
}
答案 1 :(得分:3)
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;
}
}
答案 2 :(得分:2)
您可以将Libgdx's "non-continuous rendering"作为降低Android上帧速率的替代方法。因为它的应用程序的UI线程将陷入困境,因此您的应用程序可能响应性较低(尽管睡眠时间不是很长)。
根据您的游戏,非连续渲染支持可能会让您进一步降低帧速率(任何时候图形没有变化且没有预期的输入,您不需要绘制新帧。)
答案 3 :(得分:-2)
使用可能会使用此
Thread.sleep((long)(1000/30-Gdx.graphics.getDeltaTime()));
将值30更改为您想要的FPS。