Animation Loop not working when button is held dow

2019-07-16 09:06发布

问题:

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.

回答1:

I usually do something similar to this: First load the images before the main loop starts, because reading from the hard disk is slow.

Assign the currently selected images to a variable active_images and swap them out if the player presses a key, e.g. active_images = right_images.

In the main loop you just have to check if the player moves and then increment the counter (or a timer variable) and assign the current image to the player variable: player = active_images[counter].

import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    white = pg.Color('white')

    x_change = 0
    y_change = 0
    x = 400
    y = 400
    # Load the images before the main loop starts. You could also
    # do this in the global scope.
    right_images = []
    for img_name in ['knight_right.png','knight_right1.png','knight_right2.png']:
        right_images.append(pg.image.load(img_name).convert_alpha())
    left_images = []
    for img_name in ['knight_left.png', 'knight_left1.png', 'knight_left2.png']:
        left_images.append(pg.image.load(img_name).convert_alpha())

    # This variable refers to the currently selected image list.
    active_images = left_images
    counter = 0  # There's no need for a second counter.
    player = active_images[counter]  # Currently active animation frame.

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_d:
                    x_change = 5
                    active_images = right_images  # Swap the image list.
                elif event.key == pg.K_a:
                    x_change = -5
                    active_images = left_images  # Swap the image list.
                elif event.key == pg.K_w:
                    y_change -= 5
                elif event.key == pg.K_s:
                    y_change += 5
            elif event.type == pg.KEYUP:
                if event.key == pg.K_d and x_change > 0:
                    x_change = 0
                    counter = 0  # Switch to idle pose.
                    player = active_images[counter]
                elif event.key == pg.K_a and x_change < 0:
                    x_change = 0
                    counter = 0  # Switch to idle pose.
                    player = active_images[counter]
                elif event.key == pg.K_w and y_change < 0:
                    y_change = 0
                elif event.key == pg.K_s and y_change > 0:
                    y_change = 0

        if x_change != 0:  # If moving.
            # Increment the counter and keep it in the correct range.
            counter = (counter+1) % len(active_images)
            player = active_images[counter]  # Swap the image.

        x += x_change
        y += y_change

        screen.fill(white)
        screen.blit(player, (x, y))
        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()


回答2:

Try the following code.

def Main():
    x = 400
    y = 400
    counter = 0
    counter2 = 0
    player = pygame.image.load('knight_left.png')
    rightImages = ['knight_right.png','knight_right1.png','knight_right2.png']
    leftImages =['knight_left.png', 'knight_left1.png', 'knight_left2.png']
    while True:
        x_change = 0
        y_change = 0
        keys = pygame.key.get_pressed()  #checking pressed keys
        if keys[pygame.K_d]:
            x_change += 5
            counter += 1
            if counter >= len(rightImages):
                counter = 0
            player = pygame.image.load(rightImages[counter])
        if keys[pygame.K_a]:
            x_change -= 5
            counter2 += 1
            if counter2 >= len(leftImages):
                counter2 = 0
            player = pygame.image.load(leftImages[counter2])


        x = x+x_change

        gameDisplay.fill(white)
        gameDisplay.blit(player,(x,y))
        pygame.display.update()

        clock.tick(30)

Main()


标签: python pygame