Daniel
Daniel

Reputation: 15

Pygame holding down keys

So I've recently been creating games in pygame. I'm making a new one, but the get_pressed isn't working. It works, but when I hold down a button it stops. I have to keep clicking repeatedly. (Sorry if this is a stupid question but I'm new)

Code:

keys = pygame.key.get_pressed()

if keys[pygame.K_RIGHT]:
    self.direction.x = 1
if keys[pygame.K_LEFT]:
    self.direction.y = 1

Upvotes: 0

Views: 61

Answers (1)

Rabbid76
Rabbid76

Reputation: 211278

See How can I make a sprite move when key is held down. pygame.key.get_pressed() is not an event.

You need to set the direction even if no key is pressed:

self.direction.x = 0
if keys[pygame.K_RIGHT]:
    self.direction.x += 1
if keys[pygame.K_LEFT]:
    self.direction.x -= 1

self.direction.y = 0
if keys[pygame.K_DOWN]:
    self.direction.y += 1
if keys[pygame.K_UP]:
    self.direction.y -= 1

or

self.direction.x = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
self.direction.y = keys[pygame.K_DOWN] - keys[pygame.K_UP]

Additionally, you need to call pygame.key.get_pressed() in the application loop, not the event loop.

class Player:

    def get_input(self):
    
        keys = pygame.key.get_pressed()

        self.direction.x = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
        self.direction.y = keys[pygame.K_DOWN] - keys[pygame.K_UP]

       # [...]
player = Player()

# apllication loop
run = True
while run:

    # event loop
    for event in pygame.event.get():
        # in the event loop
        if event.type == pygame.QUIT:
            run = False

    # in the application loop
    player.get_input()

    # [...]

Upvotes: 2

Related Questions