|
发表于 2023-5-8 11:35:49
|
显示全部楼层
在pygame2.3.0中, pygame.key.get_pressed() 的行为可能已经发生了变化。你的代码中的问题可能是由于按下q键时,方向键的条件被覆盖了。为了解决这个问题,可以尝试将 elif 替换为 if ,这样即使按下q键,上下左右键也会继续生效。
修改后的代码如下:
- import pygame,sys
- pygame.init()
- screen = pygame.display.set_mode((1280,720))
- image = pygame.Surface((32,64))
- image.fill('green')
- rect = image.get_rect(center = (640,360))
- direction = pygame.math.Vector2()
- pos = pygame.math.Vector2(rect.center)
- speed = 2
- clock = pygame.time.Clock()
- while True:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- pygame.quit()
- sys.exit()
- keys = pygame.key.get_pressed()
- if keys[pygame.K_UP]:
- direction.y = -1
- if keys[pygame.K_DOWN]:
- direction.y = 1
- if not keys[pygame.K_UP] and not keys[pygame.K_DOWN]:
- direction.y = 0
- if keys[pygame.K_LEFT]:
- direction.x = -1
- if keys[pygame.K_RIGHT]:
- direction.x = 1
- if not keys[pygame.K_LEFT] and not keys[pygame.K_RIGHT]:
- direction.x = 0
- if keys[pygame.K_q]:
- print('这边是重点')
- if direction.magnitude() > 0:
- direction = direction.normalize()
- pos.x += direction.x * speed
- rect.centerx = pos.x
- pos.y += direction.y * speed
- rect.centery = pos.y
- screen.fill((0,0,0))
- screen.blit(image,rect)
- pygame.display.flip()
- clock.tick(60)
复制代码
这样,按下q键时,上下左右键仍然会生效。 |
|