Trying To Change Image Of Moving Character In Every 0.25 Seconds PyGame
So i am trying to 'animate' my character in pygame by changing between 2 pictures when he walks. I tried to use the code that was mentioned here: In PyGame, how to move an image ev
Solution 1:
In pygame the system time can be obtained by calling pygame.time.get_ticks()
, which returns the number of milliseconds since pygame.init()
was called. See pygame.time
module.
Use an attribute self.walk_count
to animate the character. Add an attribute animate_time
to the class that indicates when the animation image needs to be changed. Compare the current time with animate_time
in draw()
. If the current time exceeds animate_time
, increment self.walk_count
and calculate the next animate_time
.
class Player:
def __init__(self):
self.animate_time = None
self.walk_count = 0
def draw(self):
current_time = pygame.time.get_ticks()
current_img = self.img
if self.xchange != 0:
current_img = self.walk1 if self.walk_count % 2 == 0 else self.walk2
if self.animate_time == None:
self.animate_time = current_time + 250 # 250 milliseconds == 0.25 seconds
elif current_time >= self.animate_time
self.animate_time += 250
self.walk_count += 1
else:
self.animate_time = None
self.walk_count = 0
screen.blit(current_img, (self.x, self.y))
Post a Comment for "Trying To Change Image Of Moving Character In Every 0.25 Seconds PyGame"