Search code examples
pythontimepygamewait

How to wait some time in pygame?


While I've been using time.wait in my code since I began learning Python and Pygame, I've been wondering if there are any other ways to do it and what are the advantages and disadvantages of each approach. For example, Pygame also has a pygame.time.wait. What's the difference between python's wait and pygame's wait functions? Which one is better? And are there other ways to wait some time besides using these two functions?


Solution

  • For animation / cooldowns, etc: If you want to 'wait', but still have code running you use: pygame.time.get_ticks

    class Unit():
        def __init__(self):
            self.last = pygame.time.get_ticks()
            self.cooldown = 300    
    
        def fire(self):
            # fire gun, only if cooldown has been 0.3 seconds since last
            now = pygame.time.get_ticks()
            if now - self.last >= self.cooldown:
                self.last = now
                spawn_bullet()