10

I'm currently making a game using PyGame (Python 3), and I'm looking for a way to make the game run at a fixed FPS.

Most of the game is located inside a giant while loop, where the user input is taken, sprites are rendered, etc. every tick. My goal is to be able to set a fixed FPS that will make the game run at the same speed on a fast or slow computer.

I can, of course, use the clock module in pygame:

clock = pygame.time.Clock()

and then call this every loop:

clock.tick(30)

but that will keep the game CAPPED at 30 FPS. So if I set it to 500 FPS it might still run as fast as it did before. My goal is that if I set it to 500 FPS it will run at the same SPEED as it would at 500 FPS...

So is it possible to make the game run at a fixed FPS (or make an illusion of that), regardless of the speed of the computer - or at least run at the same speed through the use of some frame-skip algorithm?

Sorry if that wording was rather confusing.

Vladimir Shevyakov
  • 2,511
  • 4
  • 19
  • 40

1 Answers1

23

The clock.tick returns the time since the last call to clock.tick. Use that value and multiply all your speeds with it when you move. Example

dt = clock.tick(60)
player.position.x += player.xSpeed * dt
player.position.y += player.ySpeed * dt

This way your player will always move at the same speed independent of what you put into the clock.tick() function.

Important is to only call clock.tick() once per frame.

Fredrik
  • 1,389
  • 1
  • 14
  • 32
  • 2
    that's not exactly what I want. I want the game to run at the same speed regardless of the speed of the computer, and to always run at the FPS I specify (or at least give an illusion of that). – Vladimir Shevyakov Feb 25 '16 at 20:42
  • 3
    That is exactly what my solution does. This is how all games does it. You use the delta time and multiply it with all your speeds, that way your characters in the game will always move at the same speed regardless of the speed of your computer. – Fredrik Feb 25 '16 at 20:45
  • 2
    And with this solution you can put any fps you want into `clock.tick()` the game will still run in the correct speed. – Fredrik Feb 25 '16 at 21:04
  • 1
    Ok, thank you, I'll try testing that again. I got some strange and memorable results the first time but that was probably an error on my part. – Vladimir Shevyakov Feb 25 '16 at 21:58
  • 2
    This answer confused me a bit, because there are 2 things going on. First of all, `click.tick(60)` will act as a sleep statement to achieve a constant framerate of in this case 60 fps. Secondly, the time elapsed is measured using `dt` -- but if you are running at a constant framerate this is not strictly necessary (you can just update by the same amount each frame). – xjcl Feb 26 '22 at 02:28