python - making loop until key is pressed in pygame -
in code, want move object while key pressed , stop when key released. however, moves 1 step when keep key pressed. here sample code. have printed (x,y) values. suggestion? thanks.
x = 20 y = 20 def keydown(evt): global x, y if evt.type == pygame.keydown: if(evt.key == pygame.k_right): x += 2.0 if(evt.key == pygame.k_left): x -= 2.0 if(evt.key == pygame.k_up): y += 2.0 if(evt.key == pygame.k_down): y -= 2.0 if evt.type == pygame.keyup: if(evt.key == pygame.k_right or evt.key == pygame.k_left): x = x if(evt.key == pygame.k_up or evt.key == pygame.k_down): y = y while true: event in pygame.event.get(): if event.type == pygame.quit: pygame.quit() sys.exit() print(x, y) keydown(event)
ps: tried posted somewhere in forum (how can make sprite move when key held down) no success.
keys = pygame.key.get_pressed() if keys[pygame.k_right]: x += 2.0 if keys[pygame.k_left]: x -= 2.0 if keys[pygame.k_up]: y += 2.0 if keys[pygame.k_down]: y -= 2.0
x = 20 y = 20 def keydown(evt): global x, y if(evt[pygame.k_right]): x += 2.0 if(evt[pygame.k_left]): x -= 2.0 if(evt[pygame.k_up]): y += 2.0 if(evt[pygame.k_down]): y -= 2.0 while true: keys = pygame.key.get_pressed() event = pygame.event.poll() if event.type == pygame.quit: pygame.quit() sys.exit() print(x, y) keydown(keys)
so first off had code never doing in keydown function
if evt.type == pygame.keyup: if(evt.key == pygame.k_right or evt.key == pygame.k_left): x = x if(evt.key == pygame.k_up or evt.key == pygame.k_down): y = y
pygame.key.get_press() returns dictionary maps pygame.key_**** booleans. iterating through give booleans, not useful you. code wrote instead work continually getting keys pressed, , changing x , y based on whether or not keys pressed.
if have more questions feel free ask, hope helped!
if still not working please post error messages
Comments
Post a Comment