我正在使用 pygame,我有基本的运动,当我按下按键时,十字准线会移动,但是我似乎无法通过按住按键来使图像移动。我还如何通过按 wasd 键使图像沿对角线移动。 干杯
# Main game loop
def main_game():
running = True
while running:
global cross_x, cross_y
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
# Draw game screen
screen.blit(background, (0, 0))
# Crosshair movement
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
cross_x = cross_x + 10
if event.key == pygame.K_a:
cross_x = cross_x - 10
if event.key == pygame.K_w:
cross_y = cross_y - 10
if event.key == pygame.K_s:
cross_y = cross_y + 10
screen.blit(crosshair, (cross_x, cross_y))
pygame.display.update()
clock.tick(60)
这是当前代码,按下按键时十字准线仅移动一次
您可以将按下的按键存储在一组中。
# Set to track pressed keys
pressed_keys = set()
# Main game loop
def main_game():
global cross_x, cross_y
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
# Add keys to the set on KEYDOWN
if event.type == pygame.KEYDOWN:
pressed_keys.add(event.key)
# Remove keys from the set on KEYUP
if event.type == pygame.KEYUP:
pressed_keys.discard(event.key)
# Handle crosshair movement
if pygame.K_d in pressed_keys:
cross_x += 10
if pygame.K_a in pressed_keys:
cross_x -= 10
if pygame.K_w in pressed_keys:
cross_y -= 10
if pygame.K_s in pressed_keys:
cross_y += 10
# Draw the game screen
screen.blit(background, (0, 0))
screen.blit(crosshair, (cross_x, cross_y))
pygame.display.update()
clock.tick(60)