我有它,这样当我的角色向左或向右移动时,他们将播放行走的动画,当他们停止移动时,他们是空闲的.动画部分工作正常,但当我松开左/右键时,它仍然在播放,播放器永远不会空闲.我的播放器动画和播放器控件的代码如下.

def animation_state():
    global player_surface, player_index, player_rect
    

    player_index += 0.15
    if player_index >= len(player_right_walk):
        player_index = 0
    
    if LEFT == True:
        player_surface = player_left_walk[int(player_index)]
    elif RIGHT == True:
        player_surface = player_right_walk[int(player_index)]


    if LEFT == False and RIGHT == False:
        player_surface = pygame.image.load('graphics/dino_idle_right.png').convert_alpha()
    
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT:
            player_surface = pygame.image.load('graphics/dino_idle_left.png').convert_alpha()
        elif event.key == pygame.K_RIGHT:
            player_surface = pygame.image.load('graphics/dino_idle_right.png').convert_alpha()

    
    screen.blit(player_surface,player_rect)

player control
def player_control():
    global LEFT, RIGHT
    player_velocity = 0
    player_gravity = 0
    

    player_gravity += 3
    player_rect.y += player_gravity
    if player_rect.bottom >= 500:
        player_rect.bottom = 500
    
    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
        player_velocity -= 11
        LEFT = True
        RIGHT = False
        if player_rect.x < -50:
            player_rect.x = 800
    elif keys[pygame.K_RIGHT]:
        player_velocity += 11
        LEFT = False
        RIGHT = True
        if player_rect.x > 800:
            player_rect.x = -50

        
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT or pygame.K_RIGHT:
                player_velocity = 0

    player_rect.x += player_velocity

推荐答案

因为如果没有按下任何键,则不会重置LEFTRIGHT.在判断密钥之前,将LEFTRIGHT设置为FALSE.根据按下的键设置LEFTRIGHT:

def player_control():
    # [...]

    keys = pygame.key.get_pressed()

    LEFT = False
    RIGHT = False
    if keys[pygame.K_LEFT]:
        player_velocity -= 11
        LEFT = True
        if player_rect.x < -50:
            player_rect.x = 800
    elif keys[pygame.K_RIGHT]:
        player_velocity += 11
        RIGHT = True
        if player_rect.x > 800:
            player_rect.x = -50

Python相关问答推荐

如何在Great Table中处理inf和nans

比Pandas 更好的 Select

如何在Python Pandas中填充外部连接后的列中填充DDL值

如何强制向量中的特定元素在Gekko中处于优化解决方案中

jsonschema日期格式

如何将泛型类类型与函数返回类型结合使用?

VSCode Pylance假阳性(?)对ImportError的react

如何在基于时间的数据帧中添加计算值

如何删除剪裁圆的对角线的外部部分

try 使用RegEx解析由标识多行文本数据的3行头组成的日志(log)文件

从`end_date`回溯,如何计算以极为单位的滚动统计量?

使用Mysql Connector通过Python创建Mysql Storec过程

如何在Python中更改按钮的值(Flask )

使用Python清除Excel中的内容

我如何在print和pd.Dataframe中返回仅在__post_init__中定义的Python数据类字段/值?

FASK集合变量未更新(HTML)中的值

如何根据两个日期之间的周数复制行?

从单个RBG图片开始创建12个多通道图像

Django FileResponse在处理大文件时崩溃

确定pymongo文档的数量