How to efficiently hold a key in Pygame?

前端 未结 7 1711
谎友^
谎友^ 2020-12-11 07:10

I\'ve found two related questions:

  • Pygame hold key down causes an infinite loop
  • pygame - on hold button down

But I want to be specific. H

7条回答
  •  臣服心动
    2020-12-11 07:35

    I like to take a slightly different approach to this problem. Instead of checking if the key is pressed and taking some action when it is, set a flag on key down and unset it on key up. Then in the function to update the player's position, check the flag and update accordingly. The following pseudo-Python explains what I'm getting at:

    if down_key_pressed:
        down_flag = True
    elif down_key_released:
        down_flag = False
    elif right_key_pressed:
        etc...
    

    This should be done in a separate loop that takes the player's input. Then in update_player_position() you can do:

    if down_flag:
        move_player_down()
    elif right_flag:
        move_player_right()
    

    This example assumes four-directional movement, but you could extend it to eight-directional fairly easily by just using if down_flag and right_flag instead.

提交回复
热议问题