简体   繁体   中英

How can I make a invincibility timer in pygame?

I have a star power-up in my game, and when it collides with the player I want an 'invincibility timer' that starts up. This timer would basically turn off all collisions for 5 seconds, and after the 5 seconds are over, they would turn on again. Is there a better way to accomplish this, and if not, how can I write this in pygame?

Use a boolean => invisibility = false Set it to true once the player colides with the star power-up.

Then in your if else statements or loops, state that if invisibility = true, no collisions will take place.

In pygame exists a timer event. Usepygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. The time has to be set in milliseconds.
Make the player invisible when the collision occurs and start the timer event. Make the player visible when you get the timer event:

player_visible = True
timer_interval = 5000 # 5 seconds
timer_event_id = pygame.USEREVENT + 1

run = True
while run :
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

         elif event.type == timer_event_id:
             player_visible = True

    # collision detection
    # [...]
    if collide:
        player_visible = False
        pygame.time.set_timer(timer_event_id, timer_interval, 1)
        

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