Reputation: 29
So recently I have been working on a project with pygame and I was starting work on my character that you could control. The player can move with the arrow keys but cannot stop when there is no keys being pressed. My solution to the was for pygame to test if the user is not pressing left, right, up, or down then the players speed would go to zero. But for some reason when I don't have and keys pressed the player speed does still not stop. I am wondering what is wrong with my if statement. Thanks for reading this and helping!
The if statement code is this:
if event.key != K_LEFT and event.key != K_RIGHT and event.key != K_DOWN and event.key != K_UP:
playerSpeed = 0
This is the full code for the movment:
#Keypress-player movement
elif event.type == KEYDOWN:
if event.key != K_LEFT and event.key != K_RIGHT and event.key != K_DOWN and event.key != K_UP:
playerSpeed = 0
if event.key == K_LEFT:
direction = LEFT
playerSpeed = .2
elif event.key == K_RIGHT:
direction = RIGHT
playerSpeed = .2
elif event.key == K_DOWN:
direction = DOWN
playerSpeed = .2
elif event.key == K_UP:
playerSpeed = .2
direction = UP
if direction == UP:
if canMoveUp == 'true':
newPlayer = {'x':coords[0]['x'], 'y':coords[0]['y']-playerSpeed}
elif direction == DOWN:
if canMoveDown == 'true':
newPlayer = {'x':coords[0]['x'], 'y':coords[0]['y']+playerSpeed}
elif direction == LEFT:
if canMoveLeft == 'true':
newPlayer = {'x':coords[0]['x']-playerSpeed, 'y':coords[0]['y']}
elif direction == RIGHT:
if canMoveRight == 'true':
newPlayer = {'x':coords[0]['x']+playerSpeed, 'y':coords[0]['y']}
Upvotes: 0
Views: 128
Reputation: 1806
You need to completely rethink your approach. There are 2 good ways of doing key-based input.
1) Have a flag for each key, set it on KEYDOWN, and unset it on KEYUP.
2) Use the currently-pressed keys dictionary that Pygame provides.
Then you can say stuff like "if keys["UP"]:". This lets you use more than one key at a time, and makes the logic simpler.
Upvotes: 1