在pygame中通过键盘事件移动精灵
我刚刚让一个精灵可以用“w、a、s、d”在窗口里移动,现在我想让这个精灵通过按空格键来“射击”。
我遇到的问题是,精灵虽然出现了,但只有在我松开空格键后才会移动。我希望精灵的子弹能在我按下空格键时一直向前飞,直到窗口的边缘,而不是等我松开空格键。
这是我的主循环:
while pygame.event.poll().type != QUIT:
screen.blit(background, (0, 0))
#"player" is the sprite moving around the window
player.move(width,height)
screen.blit(player.image, player.rect)
key = pygame.key.get_pressed()
if key[K_SPACE]:
xpos = player.rect.right
ypos = player.rect.top
shot_on_screen = True
if shot_on_screen:
xpos += 1
#"kame" is the sprite i want to move forward
screen.blit(shot.kame, (xpos, ypos))
else:
shot.x = player.rect.right
shot.y = player.rect.top
shot_on_screen = False
pygame.display.update()
我刚刚开始接触这个python-pygame的世界,虽然在提问之前查了很多手册和文档,但还是希望你们能帮帮我,谢谢。
1 个回答
0
你在每次按下K_SPACE的时候,都把xpos设置为玩家最右边的位置。这样做是不对的。试着把那行代码去掉。
if key[K_SPACE]:
ypos = player.rect.top
shot_on_screen = True
另外,我不确定你在代码的其他地方是否有检查子弹是否在屏幕上,但你发的这段代码不会把它设置为假。
if shot_on_screen:
xpos += 1
#"kame" is the sprite i want to move forward
screen.blit(shot.kame, (xpos, ypos))
else:
shot.x = player.rect.right
shot.y = player.rect.top
shot_on_screen = False # won't work. It is already False.