需要帮助Pygame KEYDOWN

时间:2015-11-25 12:55:19

标签: python pygame

只是寻求帮助,

如何调整此值,以便我的角色仅在按下右键的左键时移动。当钥匙被释放时停止?

player_x = 10
player_y = 245
player_x_change = 0

clock = pygame.time.Clock()

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
            player_x_change = -20 
            if event.key == pygame.K_RIGHT:
                player_x_change = 20

    player_x += player_x_change

1 个答案:

答案 0 :(得分:2)

您必须检查KEYUP并更改player_x_change

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player_x_change = -20 
            elif event.key == pygame.K_RIGHT:
                player_x_change = 20

        elif event.type == pygame.KEYUP:
            if event.key in (pygame.K_LEFT,pygame.K_RIGHT):
                player_x_change = 0

编辑:

如果你需要在同时按下LEFT和RIGHT时停止对象

player_x_change = 0

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player_x_change -= 20 
            elif event.key == pygame.K_RIGHT:
                player_x_change += 20

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                player_x_change += 20 
            elif event.key == pygame.K_RIGHT:
                player_x_change -= 20