Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pygame How to use walking animations

Tags:

python

pygame

When I walk Up, Down, Left, or Right I want 3 images to play while I'm walking in that direction.

player = pygame.image.load('data/down1.png')

playerX = 610
playerY = 350

while 1:
    clock.tick(30)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            return
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            return
        if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
                player = pygame.image.load('data/down1.png')
                player = pygame.image.load('data/down2.png')
                player = pygame.image.load('data/down3.png')
                playerY = playerY + 5

        screen.fill((0, 0, 0))
        screen.blit(player, (playerX, playerY))

        pygame.display.flip()

(This is part of my code btw) So is there a way I can make it so when I'm walking down it plays like an animation of the walking down images?

like image 849
user3777041 Avatar asked Jun 25 '14 21:06

user3777041


1 Answers

You can create a circular buffer with the names.

images = ['data/down1.png','data/down2.png','data/down3.png']

and then change a counter

...

if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
    player = pygame.image.load(images[counter])
    counter = (counter + 1) % len(images)
    playerY = playerY + 5
...

It will change the image while the button is pressed.

like image 160
Cristiano Araujo Avatar answered Oct 12 '22 21:10

Cristiano Araujo