How do I get my object in pygame to move by holding the button?

前端 未结 3 1506
猫巷女王i
猫巷女王i 2021-01-21 23:47

I tried using something like this but it did not work.

while running:
keys = pygame.key.get_pressed()  #checking pressed keys
if keys[pygame.K_UP]:
    y1 -= 1
i         


        
相关标签:
3条回答
  • 2021-01-22 00:13

    There are two ways to check for key input, either if they're in the event queue or checking their current state.

    Event queue

    Keys are put into the event queue when they're pressed or realesed, so you cannot directly tell if a key is held or not. There are two ways around this:

    1. Call pygame.key.set_repeat(True) before you enter the main loop. This will repeatedly put the KEYDOWN event into the event queue, as long as it's held.

    2. Introduce a velocity variable. Set the velocity to some speed when the user press down the key, and set the velocity to 0 when the user lift the key.

    For example:

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                velocity_x = -5
            elif event.key == pygame.K_RIGHT:
                velocity_x = 5
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                velocity_x = 0
            elif event.key == pygame.K_RIGHT:
                velocity_x = 0
    
    position_x += velocity_x
    

    State checking

    You get the current state of the keys by calling pygame.key.get_pressed(). You have to call one of the functions in pygame.event in order for pygame to do some required internal actions, so use pygame.event.pump() if you don't want to use the event queue. Your OS will think pygame has crashed if you don't, resulting in the game being unresponsive. Although, you usually want to handle the pygame.QUIT event, so the user can quit.

    pygame.event.pump()
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        position_x -= 5
    elif keys[pygame.K_RIGHT]:
        position_x += 5
    
    0 讨论(0)
  • 2021-01-22 00:14

    Try adding the keys to your pygame for loop. So it should look something like this...

    while running:
    for event in pygame.event.get():
        keys = pygame.key.get_pressed()  #checking pressed keys
            if keys[pygame.K_UP]:
            y1 -= 1
    
            if keys[pygame.K_DOWN]:
            y1 += 1
    
    0 讨论(0)
  • 2021-01-22 00:25

    One solution to this problem would be to use set_repeat function

    pygame.key.set_repeat(True)
    

    This will generate multiple KEYDOWN events.

    0 讨论(0)
提交回复
热议问题