I've been working with Pygame and I encountered this problem.
I have made 2 animation lists. One called rightImages
which contains images of my character walking to the right, and one called leftImages
which is the opposite. The animation works when I press the D key over (My program's controls are A is left, D is right, etc) and over again, but when I hold it down the animations do not run. Hopefully, you understand and if you don't please run the program and then maybe you will get what I am saying. Here is my code:
def Main():
x_change = 0
y_change = 0
x = 400
y = 400
counter = 0
counter2 = 0
player = pygame.image.load('knight_left.png')
while True:
rightImages = ['knight_right.png','knight_right1.png','knight_right2.png']
leftImages =['knight_left.png', 'knight_left1.png', 'knight_left2.png']
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
x_change += 5
counter += 1
if counter >= len(rightImages):
counter = 0
player = pygame.image.load(rightImages[counter])
elif event.key == pygame.K_a:
x_change -= 5
counter2 += 1
if counter2 >= len(leftImages):
counter2 = 0
player = pygame.image.load(leftImages[counter2])
elif event.key == pygame.K_w:
y_change -= 5
elif event.key == pygame.K_s:
y_change += 5
elif event.type == pygame.KEYUP:
x_change = 0
y_change = 0
x = x+x_change
y = y+y_change
gameDisplay.fill(white)
gameDisplay.blit(player,(x,y))
pygame.display.update()
clock.tick(30)
Main()
This is the code that runs through the animation loop when walking to the right.
counter += 1
if counter >= len(rightImages):
counter = 0
player = pygame.image.load(rightImages[counter])
This is for when walking to the left.
counter2 += 1
if counter2 >= len(rightImages):
counter2 = 0
player = pygame.image.load(rightImages[counter2])
If you could please tell me how to cycle through the animation lists even when the key is held down that would be awesome!
Note: I did not include all of my code.