How do I cap my framerate at 60 fps in Java?

后端 未结 10 1723
离开以前
离开以前 2021-02-07 08:01

I am writting a simple game, and I want to cap my framerate at 60 fps without making the loop eat my cpu. How would I do this?

10条回答
  •  心在旅途
    2021-02-07 08:54

    Here's how I did it in C++... I'm sure you can adapt it.

    void capFrameRate(double fps) {
        static double start = 0, diff, wait;
        wait = 1 / fps;
        diff = glfwGetTime() - start;
        if (diff < wait) {
            glfwSleep(wait - diff);
        }
        start = glfwGetTime();
    }
    

    Just call it with capFrameRate(60) once per loop. It will sleep, so it doesn't waste precious cycles. glfwGetTime() returns the time since the program started in seconds... I'm sure you can find an equivalent in Java somewhere.

提交回复
热议问题