简体   繁体   中英

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()

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()
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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM