使用 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 世界的新手,在询问之前我已经检查了很多手册和文档,希望你能提供帮助,谢谢。
I just got a sprite moving around the window using "w,a,s,d", and i want to make this sprite "shoot" by pressing the space bar.
The problem i've got is that the sprite appears but doesn't move until i release the space bar, and i want the sprite shot to go forward until the end of the window, just by pressing the space bar, not by releasing it.
This is my main loop:
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()
I'm new at this python-pygame world, i've checked a lot of manuals and documentation before asking though, hope you can help, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当按下 K_SPACE 时,您将 xpos 设置为每次循环中玩家最右边的位置。你不应该这样做。尝试删除该行。
另外,我不知道您是否正在检查镜头是否在屏幕上代码的其他位置,但您发布的代码不会将其设置为 false。
You are setting xpos to the player most right position on every loop when the K_SPACE is pressed. You shouldn't do that. Try removing that line.
Also, I don't know if you are checking if the shot is on the screen somewhere else on the code, but the code you posted will not set it to false.