python - 我在使用 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 个小时,并在互联网上搜索解决方案并得到这个,我什至查看了我的谷歌搜索的第二页,只是为了找到我的问题的一些答案。
解决方案
你错过了增加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))
推荐阅读
- python-3.x - AttributeError:模块'docx'在尝试执行.py文件时没有属性'Document'
- python - 将元数据添加到 tensorflow 冻结图 pb
- android - 当我的应用程序被销毁时,firebase 不会存储我的用户并且它会跳过登录页面
- openscenegraph - 如何在 Android 中创建 osg::Image 对象?
- r - 估算常数并创建缺失假人
- jmeter - 如何从 JMeter 中的 AMQP 请求中提取数据
- javascript - 嵌套标签时查找元素包含文本
- java - Socket IO事件多次触发NodeJS
- google-data-studio - 找不到组件 ID:gs://
- c# - 如何从 UTC 偏移量获取 DateTime