我一直在和Pygame合作,我遇到了这个问题。
我制作了2个动画列表。一个叫rightImages
,其中包含我的角色走向右边的图像,还有一个叫做leftImages
的图像是相反的。当我按下D键(我的程序的控件是A,左边是D,右边等)时,动画可以正常工作,但是当我按住它时,动画不会运行。希望你理解,如果你不理解请运行程序,那么也许你会得到我说的。这是我的代码:
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()
这是在向右走时通过动画循环运行的代码。
counter += 1
if counter >= len(rightImages):
counter = 0
player = pygame.image.load(rightImages[counter])
这是向左走的时候。
counter2 += 1
if counter2 >= len(rightImages):
counter2 = 0
player = pygame.image.load(rightImages[counter2])
如果你能告诉我如何循环播放动画列表,即使按下按键也很棒!
注意:我没有包含我的所有代码。
答案 0 :(得分:1)
请尝试以下代码。
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()
答案 1 :(得分:1)
我通常会做类似的事情:首先在主循环开始之前加载图像,因为从硬盘读取速度很慢。
将当前选定的图像分配给变量active_images
,如果玩家按下某个键,则将其换出,例如active_images = right_images
。
在主循环中,你只需检查玩家是否移动然后递增counter
(或timer
变量)并将当前图像分配给player
变量:{ {1}}。
player = active_images[counter]