What Is The Best Way To Make A Player Move At Every Interval In Pygame?
Solution 1:
I suggest using pygames event mechanics and pygame.time.set_timer()
(see here for docs).
You would do something like this:
pygame.time.set_timer(pygame.USEREVENT, 500)
and in the event loop look for the event type.
ifevent.type == pygame.USEREVENT:
If this is the only user defined event that you are using in your program you can just use USEREVENT
.
When you detect the event the timer has expired and you move your snake or whatever. A new timer can be set for another 1/2 second. If you need more accuracy you can keep tabs on the time and set the timer for the right amount of time, but for you situation just setting it for 1/2 sec each time is okay.
If you need multiple timers going and need to tell them apart, you can create an event with an attribute that you can set to different values to track them. Something like this (though I have not run this particular code snippet, so there could be a typo):
my_event = pygame.event.Event(pygame.USEREVENT, {"tracker": something})
pygame.time.set_timer(my_event , 500)
Solution 2:
You can store the moment of last move and then compare to actual time. To do it you can use perf_counter
from time
. Here is an example
last_move_time = perf_counter()
while running:
if perf_counter() - last_move_time > 0.5:
# move player
last_move_time = perf_counter()
Post a Comment for "What Is The Best Way To Make A Player Move At Every Interval In Pygame?"