也就是实现类似key_down单次触发。
for event in events: if event.type == pygame.KEYDOWN: if event.key in [pygame.K_LEFT, pygame.K_a]: xxxx() elif event.key in [pygame.K_RIGHT, pygame.K_d]: xxxx() elif event.type == pygame.JOYHATMOTION:
# 按下左方向,再松开,会触发两次JOYHATMOTION事件,分别为(-1, 0)和(0, 0) hat_x, hat_y = event.value
# 如果摇杆回到中心(x=0),重置所有状态 if hat_x == 0: locked_direction = None else: # 方向名称 direction = getHatDirection(event.value) print(direction)
isDoSelect = False # 第一次按下方向,左或右 if locked_direction is None: locked_direction = direction isDoSelect = True elif direction != locked_direction: isDoSelect = True else: # 方向跟上次一样,什么都不做(忽略左→左下→左) pass
# 触发方向切换 if isDoSelect: if direction == "right": xxxx() elif direction == "left": xxxx()
elif event.type == pygame.JOYAXISMOTION: # 手柄摇杆 - 只在"推过阈值"的瞬间触发 if event.axis == 0: # 左摇杆X轴
# 检测从"中心"到"推动"的瞬间 # 0,0.11,0.21,0.31,0.41,0.51,0.61……大概这样 if abs(event.value) > 0.5 and last_axis_value < 0.5: if not axis_triggered: if event.value > 0: #右边 xxxx() else: xxxx() axis_triggered = True else: # 摇杆回到中心,解锁 axis_triggered = False
# 记录上次x轴的值 # 这个值只在选卡界面时更新,选卡后松开会变为0,会导致下次选卡第一次进来last_axis_value < 0.5条件成立,导致跳了一下。 # 所以,在upgrade_phase切换为1时,需要设置last_axis_value值为1. last_axis_value = abs(event.value) elif event.type == pygame.JOYBUTTONDOWN: if event.button==0: xxxx()
|