鱼C论坛

 找回密码
 立即注册
查看: 4530|回复: 8

[已解决]pygame2.3.0中的key.get_pressed()问题

[复制链接]
发表于 2023-5-2 18:37:54 | 显示全部楼层
使用pygame.key.set_mods(0) 可以解决这个问题。在检查按键之前添加这一行,它会禁用所有修饰符(如shift,ctrl等)的影响。在你的代码中,在 keys = pygame.key.get_pressed() 前添加 pygame.key.set_mods(0) :

  1. import pygame,sys

  2. pygame.init()

  3. screen = pygame.display.set_mode((1280,720))

  4. image = pygame.Surface((32,64))
  5. image.fill('green')

  6. rect = image.get_rect(center = (640,360))

  7. direction = pygame.math.Vector2()
  8. pos = pygame.math.Vector2(rect.center)
  9. speed = 2

  10. clock = pygame.time.Clock()

  11. while True:
  12.     for event in pygame.event.get():
  13.         if event.type == pygame.QUIT:
  14.             pygame.quit()
  15.             sys.exit()
  16.     pygame.key.set_mods(0)  # 添加这一行
  17.     keys = pygame.key.get_pressed()

  18.     if keys[pygame.K_UP]:
  19.         direction.y = -1
  20.     elif keys[pygame.K_DOWN]:
  21.         direction.y = 1
  22.     else:
  23.         direction.y = 0

  24.     if keys[pygame.K_LEFT]:
  25.         direction.x = -1
  26.     elif keys[pygame.K_RIGHT]:
  27.         direction.x = 1
  28.     else:
  29.         direction.x = 0

  30.     if keys[pygame.K_q]:
  31.         print('这边是重点')

  32.     if direction.magnitude() > 0:
  33.         direction = direction.normalize()

  34.     pos.x += direction.x * speed
  35.     rect.centerx = pos.x

  36.     pos.y += direction.y * speed
  37.     rect.centery = pos.y

  38.     screen.fill((0,0,0))

  39.     screen.blit(image,rect)  

  40.     pygame.display.flip()

  41.     clock.tick(60)
复制代码


现在当你按下 q 键时,上下左右键不会失效。这是因为在pygame 2.3.0中,默认的键盘修饰符行为已经发生了变化。将其设置为0可禁用这些修饰符,使其恢复到预期的行为。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-2 10:06

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表