Pygame.key.get_pressed - How To Add Interval?
I have made a simple grid and a simple sprite which works as 'player'. but when i use arrow keys to move, the character moves too fast as shown in the picture below: and my questi
Solution 1:
The simplest thing to do is record the time that you processed the first event, and then suppress handling of the event again until the new time is at least some interval greater than the first instance.
Some code may make this clearer:
# In your setup set the initial time and interval
lastTime = 0
interval = 500# 500 ms# [...]while True: # Main event loopkeys = pygame.key.get_pressed()
ifkeys[pygame.K_LEFT] and (getCurrentMillis() > lastTime + interval):
lastTime = getCurrentMillis() # Save the new most-recent timeprint"Handled a keypress!"
With this, the program tracks the use of the key and only considers it again once some amount of time has passed.
The above code wont work verbatim: you need to consider the different time sources available to you and pick the one that suits you best.
You should also consider how it is you will track many different last used times: a dictionary (a defaultdict might be useful here to avoid lots of up-front adding of keys) of keys and their last clicked time might be worth using.
Post a Comment for "Pygame.key.get_pressed - How To Add Interval?"