如何使用pydirectinput实现鼠标渐变移动?
实现pydirectinput鼠标平滑渐变移动
pydirectinput内置的duration参数在不少游戏环境中无法生效,原因是它的延时实现没有适配游戏的DirectInput输入机制,导致直接瞬移。要实现平滑移动,需要手动拆分移动过程,通过多次小幅度移动配合短延时来模拟渐变效果。
改进后的相对移动代码
针对你原有的方向型相对移动需求,可以用以下方式实现平滑移动:
import pydirectinput as mouse import time def move_mouse(move, direction, dur): # 拆分移动步数,步数越多越平滑,建议50-100之间调整 total_steps = 60 step_interval = dur / total_steps # 计算每一步的移动增量 if direction == 'N': step_x, step_y = 0, -move / total_steps elif direction == 'S': step_x, step_y = 0, move / total_steps elif direction == 'W': step_x, step_y = -move / total_steps, 0 elif direction == 'E': step_x, step_y = move / total_steps, 0 else: return # 逐帧执行小步移动 for _ in range(total_steps): # 鼠标坐标为整数,需转换后执行移动 mouse.moveRel(int(step_x), int(step_y), relative=True) time.sleep(step_interval)
关键注意事项
- 步数调整:
total_steps的值决定平滑度,数值越大移动越细腻,但过高会增加CPU占用,根据游戏性能调整即可。 - 整数坐标:鼠标移动的坐标必须是整数,所以要把每步增量转为
int类型,避免无效输入。 - 自然模拟:如果需要更贴近人类的移动,可以在每步增量中加入微小的随机偏移,比如
step_x += random.uniform(-0.5, 0.5)。 - 安全机制:如果移动过程中触发pydirectinput的安全退出(鼠标移到屏幕角落),可以提前设置
mouse.FAILSAFE = False关闭该机制。
绝对坐标平滑移动(可选)
如果需要直接移动到指定绝对坐标,可使用以下函数:
import pydirectinput as mouse import time def move_to_smooth(target_x, target_y, dur): total_steps = 60 step_interval = dur / total_steps current_x, current_y = mouse.position() # 计算每帧的坐标增量 delta_x = (target_x - current_x) / total_steps delta_y = (target_y - current_y) / total_steps for _ in range(total_steps): current_x += delta_x current_y += delta_y mouse.moveTo(int(current_x), int(current_y)) time.sleep(step_interval)
内容的提问来源于stack exchange,提问作者Scared_Shyless
相关产品推荐
相关产品推荐

