Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continuously move a surface in pygame upon key press?

Tags:

python

pygame

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?

like image 818
Curious Bill Avatar asked Dec 03 '25 18:12

Curious Bill


1 Answers

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

like image 176
RafalS Avatar answered Dec 06 '25 07:12

RafalS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!