首页 > 解决方案 > 我在使用 pygame 动画时遇到问题

问题描述

我对编码很陌生,我在 pygame 中的动画遇到了一些问题,而不是移动我只看到静止图像。

import pygame
import os

pygame.init()

Stationary = pygame.image.load(os.path.join("Assets", "stationary.png"))
left = [pygame.image.load(os.path.join("Assets", "L1.png")),
        pygame.image.load(os.path.join("Assets", "L2.png")),
        pygame.image.load(os.path.join("Assets", "L3.png")),
        pygame.image.load(os.path.join("Assets", "L4.png"))
        ]
right = [pygame.image.load(os.path.join("Assets", "R1.png")),
         pygame.image.load(os.path.join("Assets", "R2.png")),
         pygame.image.load(os.path.join("Assets", "R3.png")),
         pygame.image.load(os.path.join("Assets", "R4.png"))
         ]

WIDTH, HEIGHT = 500, 300
screen = pygame.display.set_mode((WIDTH, HEIGHT))
BLACK = 0, 0, 0
vel = 0.5
stepIndex = 0
clock = pygame.time.Clock()
FPS = 60
move_left = False
move_right = False
x = 50
y = 250


def draw_screen():
    global stepIndex
    screen.fill(BLACK)
    if stepIndex >= 8:
        stepIndex = 0
    if move_left:
        screen.blit(left[stepIndex//2], (x, y))
    elif move_right:
        screen.blit(right[stepIndex//2], (x, y))
    else:
        screen.blit(Stationary, (x, y))


running = True
while running:
    clock.tick(FPS)
    draw_screen()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys_pressed = pygame.key.get_pressed()
    if keys_pressed[pygame.K_d]:
        x += vel
        move_right = True
        move_left = False
    elif keys_pressed[pygame.K_a]:
        x -= vel
        move_right = False
        move_left = True
    else:
        move_left = False
        move_right = False
        stepIndex = 0

    pygame.display.update()

pygame.quit()

我一直盯着我的代码大约 2 个小时,并在互联网上搜索解决方案并得到这个,我什至查看了我的谷歌搜索的第二页,只是为了找到我的问题的一些答案。

标签: pythonanimationpygame

解决方案


你错过了增加stepIndex

def draw_screen():
    global stepIndex
    screen.fill(BLACK)

    stepIndex += 1      # <--- this is missing
    if stepIndex >= 8:
        stepIndex = 0
    
    if move_left:
        screen.blit(left[stepIndex//2], (x, y))
    elif move_right:
        screen.blit(right[stepIndex//2], (x, y))
    else:
        screen.blit(Stationary, (x, y))

推荐阅读