使用pygame进行连续运动的问题

我试图使我的角色在按下该键的同时就一直移动,但到目前为止,每按一次该键就移动一次,并且需要释放该键才能使他再次移动。

我已经尝试使用pygame.key.get_pressed(),如图所示,但我无法弄清楚它到底出了什么问题。

def keyPressed(input_key):
    keysPressed = pygame.key.get_pressed()
    if keysPressed[input_key]:
        return True
    else:
        return False
...

run = True
while run:

    for event in pygame.event.get():
        if keyPressed(pygame.K_LEFT) and x > vel:
            x -= vel
...
评论
jeum
jeum

You have to call pygame.key.get_pressed() in the application loop rather than the main loop. The event loop is only executed when an event occurs (like pygame.KEYDOWN). But the application loop is executed in every frame.
The typical use for pygame.key.get_pressed() may look as follows:

while run:

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

    #<---| Indentation

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and x > vel:
        x -= vel
    if keys[pygame.K_RIGHT] and x < widht-vel:
        x += vel

    # [...]
点赞
评论