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