I am making a game in pygame and python and i have my movemnt code set yp like this
if (pygame.key.get_pressed() [pygame.K_a] != 0):
moving = True
xPos_change = -3
xPos += xPos_change
if (pygame.key.get_pressed() [pygame.K_d] != 0):
moving = True
xPos_change = 3
xPos += xPos_change
And then While the Boolean moving = True its playes an animation i dont want to be able to press both at the same time making your character stop if you press both. for example if im moving with a to the left and i then press a to move to the right while i am pressing a then d overrides it and moves to the right eben if im holding a because d was the last key pressed.basically i want the last pressed key to override the last pressed key.But how would i do that?
PS I hope my question is clear apprently i have a tendancey to not state my questions correctly and i get alot of backlash
Trivial solution would be just using elif
instead of if
for the second test, however then the a
key has always precedence over the d
key, which isn't ideal either.
A better solution would be to decouple the input handling from the physics simulation further. So instead of directly doing the xPos change on the key preess, you first process all the input to figure out the direction in which the user is pressing and then apply that direction to the action:
# process input
direction = 0
if (pygame.key.get_pressed() [pygame.K_a] != 0):
direction -= 1
if (pygame.key.get_pressed() [pygame.K_d] != 0):
direction += 1
# process physics
if direction == -1:
moving = True
xPos_change = -3
xPos += xPos_change
elif direction == 1:
moving = True
xPos_change = 3
xPos += xPos_change
If the user now presses both keys they cancel each other out and the direction
is 0.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.