0

I would like to achieve a frame rate as constant as possible in my Pygame game.

This answer (Setting a fixed FPS in Pygame, Python 3) explains how to give a fluent and frame-rate-independant result, but this is not the same as a constant frame rate.

What I expect is (for 30 FPS objective):

  • if processing time is less than 1/30 s, sleep the amount a time left to avoid using all CPU ressource.
  • if more, don't sleep.

One solution (but doesn't seem optimal, not sure why):

... setup pygame...
clock = pygame.time.Clock()

# Main loop
while True:
    ...do some processing...
    ...possibly not same computation time every frame...
    dt = clock.tick(0)
    if dt < 1/FPS:
        clock.tick(1/ (1/FPS - dt))

Edited clock.tick after @Rabbid76's answer.

Big Bro
  • 797
  • 3
  • 12
  • Why do you feel that your solution is not optimal? What sort of improvement are you looking for? If what you have works, it looks fine to me. – CryptoFool Feb 15 '21 at 08:47
  • Well I'm not exactly sure how the internals of pygame.Clock work, but I thought it not optimal to call `clock.tick` twice, and wondered if there was any kind of builtin way to achieve this (as it seems a common requirement). – Big Bro Feb 15 '21 at 08:49
  • 1
    Sorry for deleting my prior comment. Isn't the idea behind `clock.tick()` that you can call it with your desired frame rate, and it will do the right thing? That is, can't you replace the last three lines of your code with just `clock.tick(FPS)`? - (I only considered this after reading the desciption of what this call does in the answer given below.) – CryptoFool Feb 15 '21 at 08:52
  • You're right, I completely misunderstood what `tick` does (I thought it just slept 1/FPS seconds). Just tested, indeed the framerate is maintained whatever the previous computation. Thanks! Do you want to answer so I can accept it ? – Big Bro Feb 15 '21 at 08:58
  • Sure! I just did that. – CryptoFool Feb 15 '21 at 09:02

1 Answers1

0

I believe that you can call clock.tick() with your desired frame rate, and it will do the right thing. That is, you can replace the last three lines of your code with just clock.tick(FPS).

CryptoFool
  • 21,719
  • 5
  • 26
  • 44