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.
clock.ticktwice, and wondered if there was any kind of builtin way to achieve this (as it seems a common requirement). - Big Broclock.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 justclock.tick(FPS)? - (I only considered this after reading the desciption of what this call does in the answer given below.) - CryptoFooltickdoes (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