pygame.key.get_pressed() 中移动功能的问题
我对Python和编码很新。尝试使用Pygame编码一个简单的游戏,我发现了一个我无法在运动功能中解决的问题。
我有一个使用Pygame方法get_pressed()的函数,以设置播放器速度向量的方向(见下文)。使用此代码,如果在游戏中,我按住 a ,然后按 d 播放器表面会改变方向,即使我仍然按住 a 键,如果我做相反的话,玩家会继续向右移动,好像我不按 a 键一样。 我知道这是由于该功能中的IF语句的顺序所致,我的问题是:有没有办法在两种情况下都可以改变方向?
我真的希望这个问题很清楚,要提前感谢有人会帮助我。
设置速度方向的功能:
def get_keys(self):
self.vel = vec(0, 0)
keys = pg.key.get_pressed()
if keys[pg.K_a]:
self.vel.x = -PLAYER_SPEED
if keys[pg.K_d]:
self.vel.x = PLAYER_SPEED
if keys[pg.K_w]:
self.vel.y = -PLAYER_SPEED
if keys[pg.K_s]:
self.vel.y = PLAYER_SPEED
if self.vel.x != 0 and self.vel.y != 0:
self.vel *= 0.7071
更新功能:
def update(self)
self.get_keys()
self.pos += self.vel * self.game.dt
self.rect.centerx = self.pos.x
self.rect.centery = self.pos.y
I'm quite new with python and coding. Trying to code a simple game using pygame I have found an issue that I can't solve in my movement function.
I have a function that uses the pygame method get_pressed() in order to set the direction of the player velocity vector (see below). With this code if in the game I hold down a and then press d the player surface changes direction even if i'm still holding down the a key, while if I do the opposite the player continues moving to the right as if I don't press the a key.
I understand that this is due to the order of the if statements in the function and my question is: is there a way to make the player change direction in both cases?
I really hope that the question is clear and thanks in advance if someone will help me.
The function that sets the direction of the velocity:
def get_keys(self):
self.vel = vec(0, 0)
keys = pg.key.get_pressed()
if keys[pg.K_a]:
self.vel.x = -PLAYER_SPEED
if keys[pg.K_d]:
self.vel.x = PLAYER_SPEED
if keys[pg.K_w]:
self.vel.y = -PLAYER_SPEED
if keys[pg.K_s]:
self.vel.y = PLAYER_SPEED
if self.vel.x != 0 and self.vel.y != 0:
self.vel *= 0.7071
The update function:
def update(self)
self.get_keys()
self.pos += self.vel * self.game.dt
self.rect.centerx = self.pos.x
self.rect.centery = self.pos.y
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于您想做的事情,您必须使用键盘事件。请注意,您希望在按下某个键后立即改变方向。这就是事件。例如:
For what you want to do you have to use the keyboard events. Note that you want to change direction as soon as a key is pressed. This is and event. e.g.: