pythonperformancepython-3.xpygameframe-rate

Setting a fixed FPS in Pygame, Python 3


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.


Solution

  • clock.tick() in the Pygame documentation:

    tick()

    update the clock

    tick(framerate=0) -> milliseconds

    This method should be called once per frame. It will compute how many milliseconds have passed since the previous call.

    If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. This can be used to help limit the runtime speed of a game. By calling Clock.tick(40) once per frame, the program will never run at more than 40 frames per second.

    Note that this function uses SDL_Delay function which is not accurate on every platform, but does not use much CPU. Use tick_busy_loop if you want an accurate timer, and don't mind chewing CPU.

    So the clock.tick() returns the time since the last call to clock.tick(), use that value to 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 regardless of what you put into the clock.tick() function