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.