Search code examples
pythonpygameclockframe-rate

How to have unlimited FPS and still control the FPS of your program in Pygame?


I did some research and found this: Setting a fixed FPS in Pygame, Python 3 and this: pygame clock.tick() vs framerate in game main loop. It is similar to what I am asking.

So the clock.tick(FPS) caps the program to run at that FPS. The reason you do this is so you can control the FPS of the program and it makes it easier for time stuff like waits.

But how can I unlimited FPS and still control my FPS for time stuff like waits? From my understanding, this is not possible, due to the fact that clock.tick(FPS) caps the FPS and while not adding it in means unlimited FPS but you not being able to control the FPS.

So it seems to be a question of weather to cap you FPS for control or have your program run as fast as possible, but without control.

In conclusion, what I am asking is four questions;

  1. Pros and cons of capping your FPS
  2. Pros and cons of not capping your FPS and going on with the natural FPS of your program
  3. Is it possible to have unlimited FPS and still control my FPS for time stuff like waits?
  4. If so, how?

Solution

  • You have to calculate the movement per frame depending on the frame rate.

    pygame.time.Clock.tick returns the number of milliseconds since the last call. When you call it in the application loop, this is the number of milliseconds that have passed since the last frame. When you call it without a parameter (framerate=0), the FPS are unlimited.

    Define the distance in pixels that the player should move per second (move_per_second). Then compute the distance per frame in the application loop:

    move_per_second = 500 # 500 is just an example and means 500 pixels/second
    
    run = True
    clock = pygame.time.Clock()
    while run:
        ms_frame = clock.tick() # get the milliseconds passed since the last frame
        
        move_per_frame = move_per_second * ms_frame / 1000  
        
        # [...]
    

    However, with this approach, you are wasting CPU time and you won't see a noticeable difference. The downside is that you don't have a constant frame rate and you have to calculate all animations and movements depending on the time that has passed in the last frame.