Reputation: 13
I'm fairly new to using Python, and I'm trying to get a hit timer so that in my game when my player is hit, it needs to wait a couple seconds before he can be hit again.
I thought I could just do something like:
while hitTimer > 0:
hitTimer -= 1
and being hit resets the counter to 10
, and requiring the counter to be > 0
to be able to be hit again, but it goes way to fast.
I tried using very small numbers like -= .00005
but that just makes my program lag bad.
How can I make it so it takes away 1 per second or something like that?
Thanks for any help.
Upvotes: 1
Views: 391
Reputation: 6750
In order to check for exactly 10 seconds, do this:
import time
# record when person was first hit.
previousHit = time.time()
if time.time() - previousHit > 10:
# The rest of your logic for getting hit.
previousHit = time.time() # Reset the timer to get the hit again.
Upvotes: 4
Reputation: 1344
You just record the time someone was hit, using time.time()
:
import time
lastHit = time.time()
And then compare the current time against lastHit
:
if time.time() - lastHit > NUMBER_OF_SECONDS:
# ... do seomthing about getting hit ...
lastHit = time.time()
Upvotes: 1
Reputation: 993
Use time.clock()
to check the time and time.sleep()
to wait.
Never rely on CPU speed for timing code.
Upvotes: 2