简体   繁体   中英

How do I use the clock/ticks function in Pygame to spawn another object after a certain amount of time?

class Sideways:
"""Overall class to manage game assets"""

    def __init__(self):
    """Initialize the game and create game resources"""
    pygame.init()
    self.screen = pygame.display.set_mode((1200, 600))
    self.screen_rect = self.screen.get_rect()
    pygame.display.set_caption("Pew Pew")
    self.bg_color = (204, 255, 255)
    self.ship = Ship(self)
    self.moving_up = False
    self.moving_down = False
    self.moving_left = False
    self.moving_right = False
    self.bullets = pygame.sprite.Group()
    self.aliens = pygame.sprite.Group()


    FIRE_EVENT  = pygame.USEREVENT + 1  # This is just a integer.
    pygame.time.set_timer(FIRE_EVENT, 1000)  # 1000 milliseconds is 1 seconds.
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
        elif event.type == FIRE_EVENT:  # Will appear once every second.
            self._create_fleet()

I'm trying to spawn another ship in pygame after a certain interval of time.

I just learned about the clock/ticks function from my previous question being directed to another thread that showed me it. Thank you. I tried to incorporate that into my code during this section.

However, when I run it, the game freezes up and crashes as if it's spawning too many things at the same time to handle and overloads. How would I manage to use this function correctly?

You must create the objects in the application loop, but not in a separate loop. This extra loop freezes your system. In general, if you want to control something over time in pygame, you have two options:

  1. Usepygame.time.get_ticks() to measure time and and implement logic that controls the object depending on the time.

  2. Use the timer event. Usepygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. Change object states when the event occurs.

For example see Spawning multiple instances of the same object concurrently in python or create clock and do action at intervals and many more similar answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM