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?
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.
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)
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 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.
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)