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

前端 未结 4 2048
清酒与你
清酒与你 2021-01-03 11:36

I am developing a little game for android with libgdx and want to limit the fps to 30 to save battery. The problem is that it doesn\'t work. The fps just drops from 60 to 56

4条回答
  •  自闭症患者
    2021-01-03 12:03

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

提交回复
热议问题