I am trying to make a game where I can move a ship left and right by pressing down on the left and right arrow keys. The code you see below is what I currently have:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
self.ship_image_rect.x += 2
if event.key == pygame.K_LEFT:
self.ship_image_rect.x -= 2
But instead of continuous movement when I press the right or left arrow key, it moves once and stops. I have to press the arrow keys repeatedly for any meaningful movement, which is definitely not what I want to do.
How can I improve this code so that my ship will move continuously in either direction upon either arrow key being pressed?
You have to use:
keys=pygame.key.get_pressed()
this returs a list of booleans representing the whole keyboard. Checking if LEFT_ARROW was pressed in current loop iteration:
if keys[K_LEFT] is True:
See this answer: https://stackoverflow.com/a/16044380/9392216
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With