Making a time delay in Pygame based on FPS

Viewed 236

Every single tutorial or answer I see about making a time delay is based on pygame ticks, which means that the delay will never be exactly the length you want it to be (not to mention half the time I'm not even sure how the code actually delays anything). What would be a good way to make something not happen until a certain amount of time has passed, but based on how many frames have passed rather than milliseconds?

Just an extra note since this was marked as a duplicate- the question this was a "duplicate" of was asking about using pygame ticks, this about timing based on frames rather than milliseconds.

2 Answers

You could have a counter in your main while loop that increments every iteration, and have an if that makes something happen if the counter exceeds a certain number, something like:

ctr = 0
frames = 100
while True:
    if ctr >= frames:
        make_something_happen()
    ctr += 1
    handle_pygame_stuff()

Use pygame.time.get_ticks() to return the number of milliseconds since pygame.init() was called. Calculate the point in time after something has to happen. Do somthong after the current time is greater than the calculated point of time:

current_time = pygame.time.get_ticks()
start_time = current_time + delay_time

run = True
while run:
    current_time = pygame.time.get_ticks()

    # [...]

    if current_time >= start_time :
        # do something
        # [...]

    # [...]

If you don't want to use pygame.time.get_ticks() you need to summarize the time for each frame. However FPS are inaccurate. Even if you use pygame.time.Clock.tick the FPS will be inaccurate and you will need to get the delta time for each frame from tick():

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

clock = pygame.time.Clock()
passed_time = 0

while True:
    passed_time += clock.tick(100)

    # [...]

    if passed_time > delay_time:
        # do something
        # [...]
Related