如何阻止精灵使用Pygame对角移动?

问题描述 投票:0回答:1

我正在制作蛇游戏。每当我按箭头键向一个方向移动然后按另一个方向的键,蛇就会对角线。 (例如,如果我先按下然后按下。)即使释放了上一个键,也会发生这种情况。我怎么能阻止这个?

# x and y marks the player's position

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_LEFT:
        x_change = -10
    if event.key == pygame.K_RIGHT:
        x_change = 10
    if event.key == pygame.K_UP:
        y_change = -10
    if event.key == pygame.K_DOWN:
        y_change = 10
    x += x_change
    y += y_change
python pygame sprite game-development
1个回答
3
投票

我添加了y_change = 0x_change = 0来重置值以仅保持正交移动。

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_LEFT:
        x_change = -10
        y_change = 0
    if event.key == pygame.K_RIGHT:
        x_change = 10
        y_change = 0
    if event.key == pygame.K_UP:
        y_change = -10
        x_change = 0
    if event.key == pygame.K_DOWN:
        y_change = 10
        x_change = 0
    x += x_change
    y += y_change
© www.soinside.com 2019 - 2024. All rights reserved.