[英]Limit FPS in Libgdx game with Thread.sleep() doesn't work
我正在使用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);
}
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秒不是真的那么長)。
根據您的游戲,非連續渲染支持可能會讓您進一步降低幀速率(任何時候圖形沒有變化且沒有預期輸入,您不需要繪制新幀)。
使用可能會使用此
Thread.sleep((long)(1000/30-Gdx.graphics.getDeltaTime()));
將值30更改為您想要的FPS。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.