pygame - Cant figure out how to limit how many keys can pressed in my python game -


i making game in pygame , python , have movemnt code set yp 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 while boolean moving = true playes animation dont want able press both @ same time making character stop if press both. example if im moving left , press move right while pressing d overrides , moves right eben if im holding because d last key pressed.basically want last pressed key override last pressed key.but how that?

p.s hope question clear apprently have tendancey not state questions correctly , alot of backlash

trivial solution using elif instead of if second test, a key has precedence on d key, isn't ideal either.

a better solution decouple input handling physics simulation further. instead of directly doing xpos change on key preess, first process input figure out direction in user pressing , apply direction 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 user presses both keys cancel each other out , direction 0.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -