在按键的同时连续移动物体时出现问题。
据我所知,pygame事件仅在接收到新信号时触发,并且按下的键不是每帧继续的信号。从下面的代码中,当我按 w 时,对象仅在按下和释放按键时移动。只要我按下按键,我就无法移动物体。我也通过检查event.key
而不是检查get_pressed()
列表来尝试if语句,但我得出了相同的结果。
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
keys = pygame.key.get_pressed()
print(keys[pygame.K_w])
if keys[pygame.K_w] and keys[pygame.K_d]:
x_change = 3
x += x_change
y_change = -3
y += y_change
elif keys[pygame.K_w] and keys[pygame.K_a]:
x_change = -3
x += x_change
y_change = -3
y += y_change
elif keys[pygame.K_s] and keys[pygame.K_d]:
x_change = 3
x += x_change
y_change = 3
y += y_change
elif keys[pygame.K_s] and keys[pygame.K_a]:
x_change = -3
x += x_change
y_change = 3
y += y_change
elif keys[pygame.K_a]:
x_change = -3
x += x_change
elif keys[pygame.K_d]:
x_change = 3
x += x_change
elif keys[pygame.K_w]:
y_change = -3
y += y_change
elif keys[pygame.K_s]:
y_change = 3
y += y_change
#ERASE OLD
screen.fill(WHITE)
#FILL NEW
all_sprites_list.draw(screen)
wall.changePosition(x,y)
player.draw(start_x,start_y)
pygame.display.update()
clock.tick(60)
答案 0 :(得分:0)
看起来行keys = pygame.key.get_pressed()
和以下行都在事件循环中,这意味着它们仅在事件队列中的每个事件中执行一次。它们实际上应该在外部while循环中,所以只需要这些行:
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and keys[pygame.K_d]:
x_change = 3
# etc.
您还可以稍微缩短代码:
x_change = 3
y_change = 3
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
x += -x_change
elif keys[pygame.K_d]:
x += x_change
if keys[pygame.K_w]:
y += -y_change
elif keys[pygame.K_s]:
y += y_change
另一种方法是删除key.get_pressed
行,只需在事件循环中设置x_change
和y_change
:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
x_change = 3
# etc.
elif event.type == pygame.KEYUP:
if event.key == pygame.K_d and x_change > 0:
x_change = 0
# etc.