Limit FPS in Libgdx game with Thread.sleep() doesn't work

倖福魔咒の 提交于 2019-11-30 16:02:09

Use might use this

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

change the value of 30 to FPS you want.

I have found a solution on the Internet and modified it a bit. It works perfect! Just add this function to your 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();
    }
}

And then in your render function:

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;
    }
}

You might look into Libgdx's "non-continuous rendering" as an alternative way of reducing the frame rate on Android. As it stands your app's UI thread will be stuck sleeping and so your app may be a bit less responsive (though sleeping for a 30th of a second isn't really that long).

Depending on your game the non-continuous rendering support might let you reduce the frame rate even further (any time there is no change to the graphics and no input expected, you do not need to draw new frames).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!