Reputation: 17
I made this thinking that it would works, but it doesn't XD it only moves the image one time per click Help me please
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
while event.type == pygame.KEYDOWN:
right == K_RIGHT
left == K_LEFT
if right == 1
posX += velocidad
elif lef == 1:
posX -= velocidad
Upvotes: 1
Views: 105
Reputation: 79
I think you want to used pygame.key.get_pressed()
as follows.
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pressed_keys = pygame.key.get_pressed()
if pressed_keys[K_RIGHT]:
posX += velocidad
if pressed_keys[K_LEFT]:
posX -= velocidad
event.type == pygame.KEYDOWN only catches when a key is first pressed down. If you want to use this you could switch some attribute like your_object.moving_right = True. Then use keyup to turn it off again.
Upvotes: 1
Reputation: 1880
Overall, I think what you want is to check event.key
with an if statement.
However there are multiple problems (both structural and syntactic) with your code. event.type
doesn't change, so using while
doesn't make sense (and this will run forever and make your program hang). I'm not sure what your intent is with the == 1
comparisons, as K_RIGHT and K_LEFT are arbitrary constants for key code values. Not to mention that right == K_RIGHT
is an expression that does nothing (did you mean right = K_RIGHT
?) and you've got a clear typo with lef
. I think the closest working code to the structure you've provided (assuming the other code not shown also works) would look something like this:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
right = K_RIGHT
left = K_LEFT
if event.key == right:
posX += velocidad
elif event.key == left:
posX -= velocidad
Upvotes: 0