0

so I'm trying to make a loop so that when my fire button is held down, it shoots every 1/2 second.

I've tried the time.wait(0.5), but it freezes my entire game fore 1/2 a second.

here's some code i tried

if event.type == KEYDOWN and event.key == K_SPACE:
            fighter.fire()
            time.wait(0.5)
            if event.type == KEYDOWN and event.key == K_SPACE:
                fighter.fire()

what i expect is fore the code to wait 0.5 seconds, then shoot again, but I'm still working on getting it to loop. What happens now is my game freezes for the specified time, then resumes, but the projectile is two stacked ontop of each other. thanks for any help

Community
  • 1
  • 1
  • what are you using for the key events? Also, because of what you mentioned, what exactly happens in fire()? – Banana Jul 24 '19 at 09:20

2 Answers2

0

It's normal it freezes, time.wait(0.5) makes your program sleep for a half second.

You should either look into multithreading, or if your loop structure makes it possible you can just store :

import time
previous = time.time()

in a variable, and on the next iteration of the loop, if

time.time() - previous > 0.5

Then you fire.

I hope that will help you

Alex_6
  • 259
  • 4
  • 16
0

As @Alex_6 said, you can try multithreading.

time.wait, time.sleep froze the whole program so you can do anything unless you release the key you are using to fire.

There's a github post same as this. https://github.com/drjones2010/space-invaders

I haven't tried it myself, but it's worth the read.

Edit: Here some another reference for your study Get smooth motion by multi-threading Python turtle graphics

Nikko Bobier
  • 100
  • 11