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

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

    If you are using Java Swing the simplest way to achieve a 60 fps is by setting up a javax.swing.Timer like this and is a common way to make games:

    public static int DELAY = 1000/60;
    
    Timer timer = new Timer(DELAY,new ActionListener() {
        public void actionPerformed(ActionEvent event) 
        {
          updateModel();
          repaintScreen();
        }
    });
    

    And somewhere in your code you must set this timer to repeat and start it:

    timer.setRepeats(true);
    timer.start();
    

    Each second has 1000 ms and by dividing this with your fps (60) and setting up the timer with this delay (1000/60 = 16 ms rounded down) you will get a somewhat fixed framerate. I say "somewhat" because this depends heavily on what you do in the updateModel() and repaintScreen() calls above.

    To get more predictable results, try to time the two calls in the timer and make sure they finish within 16 ms to uphold 60 fps. With smart preallocation of memory, object reuse and other things you can reduce the impact of the Garbage Collector also. But that is for another question.

提交回复
热议问题