Search code examples
pythontimepygamepygame-clockpygame-tick

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 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?


Solution

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