How can I make a invincibility timer in pygame?

Question:

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?

Asked By: Rohit Sangishetty

||

Answers:

Use a boolean => invisibility = false

Set the boolean to true once the player collides with the star power-up.

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

Answered By: CallMeAdmiral

In pygame exists a timer event. Use pygame.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)
        
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.