如何解决PyGame 角色不向左移动
我有以下问题:角色没有正确向左移动。我尝试调试并看到在 drawfrantz 函数中 moveLeft 不是真的,但在 while 游戏循环中却是这样。我尝试了很多,比如设置全局等等,但似乎根本不起作用。我遵循了 yt 教程,这是链接 https://www.youtube.com/watch?v=9Kh9s9__ywo
import pygame
pygame.init()
display_width = 1280
display_height = 720
x = 250
y = 250
veLocity = 10
moveRIGHT = False
moveLeft = False
stepIndex = 0
screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Frantz Reichts!")
clock = pygame.time.Clock()
frantz_stationary = pygame.image.load("assets/frantz/trash_ting3.png")
frantz_going_left = [None]*10
for indexofpic in range(1,9):
frantz_going_left[indexofpic-1] = pygame.image.load("assets/frantz/L" + str(indexofpic) + ".png")
indexofpic = (indexofpic + 1)
frantz_going_right = [None]*10
for picindex in range(1,9):
frantz_going_right[picindex-1] = pygame.image.load("assets/frantz/R" + str(picindex) + ".png")
picindex = (picindex + 1)
# Images #
stage1full = pygame.image.load("assets/WholeStage.png")
karavane = pygame.image.load("assets/Karavane.png")
def DrawFrantz():
global stepIndex
if stepIndex >= 8:
stepIndex = 0
if moveLeft == True:
screen.blit(frantz_going_left[stepIndex],(x,y))
stepIndex += 1
elif moveRIGHT == True:
screen.blit(frantz_going_right[stepIndex],y))
stepIndex += 1
else:
screen.blit(frantz_stationary,y))
while(True): #Game Loop
screen.fill((0,0))
screen.blit(stage1full,(0,0))
screen.blit(karavane,0))
DrawFrantz()
userInput = pygame.key.get_pressed()
if userInput[pygame.K_a]:
x -= veLocity
moveLeft = True
moveRIGHT = False
if userInput[pygame.K_d]:
x += veLocity
moveLeft = False
moveRIGHT = True
else:
moveLeft = False
moveRIGHT = False
stepIndex = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.time.delay(100)
pygame.display.update()
clock.tick(60)
解决方法
我还没有测试过,但我猜你需要一个 elif
而不是 if
:
userInput = pygame.key.get_pressed()
if userInput[pygame.K_a]:
x -= velocity
moveLeft = True
moveRIGHT = False
elif userInput[pygame.K_d]: # <- here elif instead of if
x += velocity
moveLeft = False
moveRIGHT = True
else:
moveLeft = False
moveRIGHT = False
stepIndex = 0
否则,即使您按下 else
按钮,末尾的 moveLeft
也会将布尔值 False
重置为 K_a
。
@Valentino 的回答是正确的。不过,我建议简化代码。
设置一个 move_x
变量,当按下 right 时为 1,按下 left 时为 -1。被按下。如果没有或同时按下两个按钮,则变量为 0。使用 move_x
变量设置 moveLeft
、moveRIGHT
并更改 x
和 stepIndex
:
userInput = pygame.key.get_pressed()
move_x = userInput[pygame.K_d] - userInput[pygame.K_a]
moveLeft = move_x < 0
moveRIGHT = move_x > 0
x += move_x * velocity
if move_x = 0:
stepIndex = 0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。