H.Dai
H.Dai

Reputation: 19

python pygame key held down

I am trying to make a plane keep moving left when hold left key down, I am using pygame.key.get_pressed(), but only response once just like normal pygame.KEYDOWN only print 'move to right ' once

Can anyone help please?

def key_control(hero_temp):
    for event in pygame.event.get():

        if event.type == pygame.QUIT:
        print('Game Exit')
        exit()

        key_state = pygame.key.get_pressed()
        if key_state[pygame.K_RIGHT]:
            print('move to right')
            hero_temp.x += 10
        if key_state[pygame.K_LEFT]:
            print('move to left')
            hero_temp.x -= 10
        if key_state[pygame.K_UP]:
            print('move to top')
            hero_temp.y -= 10
        if key_state[pygame.K_DOWN]:
            print('move to right')
            hero_temp.y += 10
        if key_state[pygame.K_SPACE]:
            print('space/shoot')
            hero_temp.fire()

Upvotes: 0

Views: 1007

Answers (2)

Leon Z.
Leon Z.

Reputation: 572

You are only calling key_state = pygame.key.get_pressed() inside you loop where you iterate over every event. Simply take it out of there and it should work.

The problem is that it will only check for the pressed buttons if there was a new event. If there was no new event it won't check the pressed buttons and the code won't be executed

def key_control(hero_temp):
    key_state = pygame.key.get_pressed()
    if key_state[pygame.K_RIGHT]:
        print('move to right')
        hero_temp.x += 10
    if key_state[pygame.K_LEFT]:
        print('move to left')
        hero_temp.x -= 10
    if key_state[pygame.K_UP]:
        print('move to top')
        hero_temp.y -= 10
    if key_state[pygame.K_DOWN]:
        print('move to right')
        hero_temp.y += 10
    if key_state[pygame.K_SPACE]:
        print('space/shoot')
        hero_temp.fire()

    for event in pygame.event.get():
        # Only gets run if there are new events
        if event.type == pygame.QUIT:
            print('Game Exit')
            exit()

Upvotes: 1

H.Dai
H.Dai

Reputation: 19

def key_control(hero_temp):
    key_state = pygame.key.get_pressed()
    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            print('Game Exit')
            exit()

        if key_state[pygame.K_RIGHT]:
            print('move to right')
            hero_temp.x += 10
        if key_state[pygame.K_LEFT]:
            print('move to left')
            hero_temp.x -= 10
        if key_state[pygame.K_UP]:
            print('move to top')
            hero_temp.y -= 10
        if key_state[pygame.K_DOWN]:
            print('move to right')
            hero_temp.y += 10
        if key_state[pygame.K_SPACE]:
            print('space/shoot')
            hero_temp.fire()

Upvotes: 0

Related Questions