简体   繁体   中英

How to make a slower timer? (Python)

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.

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.

Use time.clock() to check the time and time.sleep() to wait.

Never rely on CPU speed for timing code.

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()

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