嘿伙计们,我在制作游戏时遇到了一些问题....我希望在图像每次改变时移动我的角色"步骤"它看起来像一个动画......
我一直在努力工作几个小时,但到目前为止我唯一做的就是移动炭,但所有图像都在移动时立即绘制
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
currentimageleft = 1
gamedisplay.blit(background, (0,0))
if currentimageleft == 1:
gamedisplay.blit(temp1, (template_x, template_y), (g1x, g1y, box, box))
template_x -= moveit
currentimageleft += 1
if currentimageleft == 2:
gamedisplay.blit(temp1, (template_x, template_y), (g2x, g2y, box, box))
template_x -= moveit
currentimageleft += 1
if currentimageleft == 3:
gamedisplay.blit(temp1, (template_x, template_y), (g3x, g3y, box, box))
template_x -= moveit
currentimageleft += 1
if currentimageleft == 4:
gamedisplay.blit(temp1, (template_x, template_y), (g4x, g4y, box, box))
template_x -= moveit
currentimageleft = 1
pygame.display.update()
答案 0 :(得分:1)
使用elif
进行后续比较,以便每次迭代只完成一次。
答案 1 :(得分:0)
由于您在每个currentimgeleft
块中递增if
,因此它会触发该行下一个if
块。您只需要一个触发每个帧,因此将if
切换到elif
除了第一个之外的所有帧,然后每次K_LEFT
按钮时只有一个触发按下键盘。像这样
if currentimageleft == 1:
# code
elif currentimageleft == 2:
# code
...
但是,请注意,每次为keypress输入较大的currentimageleft
语句时,您都要设置if
。这将确保您始终最终使用动画的第一个精灵。您可能希望将currentimageleft
与类变量关联,方法是在__init__
中将其声明为
def __init__(self, ...):
# other code, including possible parent constructors
self.currentleftimage = 1
# more code
然后,您将使用self.currentimageleft
而不是currentimageleft
来访问您的变量。这样,您就可以在按键按下检测时使用else
或elif
条款(代码段中的if
外部)将self.currentleftimage
变量重置为{{ 1}}允许您以这种方式跟踪运动。
您可能还会发现this other answer on the equivalent form of switch
in Python有趣,尽管对1
条款的多次调用也非常正常,并且在许多情况下可能会导致更清晰的代码。