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

后端 未结 10 1712
离开以前
离开以前 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:59

    I took the Game Loop Article that @cherouvim posted, and I took the "Best" strategy and attempted to rewrite it for a java Runnable, seems to be working for me

    double interpolation = 0;
    final int TICKS_PER_SECOND = 25;
    final int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
    final int MAX_FRAMESKIP = 5;
    
    @Override
    public void run() {
        double next_game_tick = System.currentTimeMillis();
        int loops;
    
        while (true) {
            loops = 0;
            while (System.currentTimeMillis() > next_game_tick
                    && loops < MAX_FRAMESKIP) {
    
                update_game();
    
                next_game_tick += SKIP_TICKS;
                loops++;
            }
    
            interpolation = (System.currentTimeMillis() + SKIP_TICKS - next_game_tick
                    / (double) SKIP_TICKS);
            display_game(interpolation);
        }
    }
    

提交回复
热议问题