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 every 3 seconds without using the sleep function? but it didn't turn out too well. In fact my character only uses one image when walking. here the part of the code and some variables:
- self.xchange: change on x axis
- self.img: image for when the character stands still
- self.walk1 and self.walk2: the two images i am trying to use to animate my character
- self.x and self.y are the cordinates screen is the surface
.
def draw(self):
self.clock = time.time()
if self.xchange != 0:
if time.time() <= self.clock + 0.25:
screen.blit(self.walk1, (self.x, self.y))
elif time.time() > self.clock + 0.25:
screen.blit(self.walk2, (self.x, self.y))
if time.time() > self.clock + 0.50:
self.clock = time.time()
else:
screen.blit(self.img, (self.x, self.y))
Why isn't it working?
In pygame the system time can be obtained by calling
pygame.time.get_ticks()
, which returns the number of milliseconds sincepygame.init()
was called. Seepygame.time
module.Use an attribute
self.walk_count
to animate the character. Add an attributeanimate_time
to the class that indicates when the animation image needs to be changed. Compare the current time withanimate_time
indraw()
. If the current time exceedsanimate_time
, incrementself.walk_count
and calculate the nextanimate_time
.