You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过win32api(mouseeventf_move)实现鼠标平滑慢速移动

游戏内鼠标平滑移动实现方案

你的问题在于直接通过大位移跳跃加固定sleep的方式移动鼠标,这种方式本质是跳跃式移动,而非连续的平滑位移,自然会显得生硬。下面是具体的解决思路和代码实现:

核心改进点

  • 将A到B的总位移拆分为连续的微小步长,模拟人手移动的连续轨迹
  • 用高精度时间控制替代time.sleep,保证移动速度均匀
  • 可选加入缓动函数,让移动更贴近真实操作的加速度变化

代码实现

首先导入依赖库:

import win32api
import win32con
import keyboard
import time

平滑移动函数

def smooth_mouse_move(target_x, target_y, duration=1.0):
    # 获取鼠标当前位置
    start_x, start_y = win32api.GetCursorPos()
    # 计算总偏移量
    total_delta_x = target_x - start_x
    total_delta_y = target_y - start_y
    
    start_time = time.perf_counter()
    while True:
        # 计算已流逝时间占总时长的比例
        elapsed = time.perf_counter() - start_time
        if elapsed >= duration:
            # 最后一步直接定位到目标点,避免误差
            win32api.SetCursorPos((target_x, target_y))
            break
        
        # 进度值(0到1),这里用线性插值,可替换为缓动函数
        progress = elapsed / duration
        # 可选:ease-in-out缓动,模拟先加速后减速
        # progress = progress * progress * (3 - 2 * progress)
        
        # 计算当前帧的鼠标位置
        current_x = start_x + total_delta_x * progress
        current_y = start_y + total_delta_y * progress
        
        # 直接设置绝对位置,比相对移动更精准
        win32api.SetCursorPos((int(current_x), int(current_y)))
        
        # 控制帧率,避免CPU过载
        time.sleep(0.001)

主循环调用

while True:
    if keyboard.is_pressed("Alt"):
        # 示例:1秒内从当前位置移动到(1000, 500)
        smooth_mouse_move(1000, 500, duration=1.0)
    # 降低主循环CPU占用
    time.sleep(0.01)

关键细节说明

  1. 为什么不用mouse_event?
    mouse_event的MOUSEEVENTF_MOVE是相对位移,需要累计计算每一步的偏移,容易产生误差;而SetCursorPos直接设置绝对坐标,更适合平滑移动场景。

  2. 时间控制的优势
    time.perf_counter()是Python中精度最高的时间函数,能准确计算移动时长,避免time.sleep()精度不足导致的速度不均问题。

  3. 缓动函数的作用
    注释中的ease-in-out缓动函数可以让鼠标移动先加速、后减速,完全模拟人手操作的自然轨迹,比匀速移动更真实。

内容的提问来源于stack exchange,提问作者JorgTV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 00:25:22