Search code examples
pythonpygamepygame-clockpygame-tick

How to create timers in pygame efficiently?


I want to spawn an enemy every (some number) seconds, say 5.

I could do:

start_time = pygame.time.get_ticks()
if pygame.time.get_ticks() - start_time >= (some number):
    spawn_enemy()

But there's one problem with that: when I change the FPS (clock.tick()) from 120 to say 60 then the enemy spawn rate will remain the same.

I could also just make a variable:

var = 0
while True:
    var += 1
    if var >= (some number):
        spawn_enemy()

But that seems like bad practice to me.


Solution

  • pygame.time.get_ticks() measures the time. It doesn't relay on the frames per second.

    You can define a time span. When the time span is exceeded then spawn an enemy and increment the time:

    next_enemy_time = 0
    
    run = True
    while run:
        # [...]
    
        if pygame.time.get_ticks() > next_enemy_time:
            next_enemy_time += 5000 # 5 seconds
            spawn_enemy() 
            
        # [...]
    

    Alternatively you can use a timer event. Use pygame.time.set_timer() to repeatedly create an USEREVENT. e.g.:

    time_delay = 5000 # 5 seconds
    timer_event = pygame.USEREVENT + 1
    pygame.time.set_timer(timer_event, time_delay)
    
    run = True
    while run:
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
    
             elif event.type == timer_event:
                 spawn_enemy() 
    
        # [...]