2

I am practicing on pygame and I was wondering how can we do so that the framerate does not affect the speed of execution of the game

I would like FPS to not be locked and the game to always run at the same speed.

Until now I used the pygame.time.Clock.tick function but the speed of the character was changing depending on the number of FPS, which I don't want.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Tangax
  • 43
  • 5

1 Answers1

4

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. Multiply the objects speed by the elapsed time per frame to get constant movement regardless of FPS.

For instance define the distance in number of pixel, which the player should move per second (move_per_second). Then compute the distance per frame in the application loop:

move_per_second = 500
FPS = 60
run = True
clock = pygame.time.Clock() 
while run:
    ms_frame = clock .tick(FPS)
    move_per_frame = move_per_second * ms_frame / 1000  

    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 1
    @Tangax It depends on. Do you mean you want to compute the positions in a different thread? Note, for a smooth movement, the positions of the objects have to be computed at least once per frame. If the position does not change it is not necessary to update the display and if the display is not updated it is not necessary to update the position. Do not over complicate the game process. The easiest solution is one loop. – Rabbid76 Apr 21 '20 at 20:34