Monday, June 25, 2012

Python: Glide, instead of move, mouse cursor from one point to another

I couldn't find a function in pywin32 to smoothly glide a pointer from one point to another, instead of simply "moving" the cursor by making it jump from its current position to a given position.  I needed a way to make the mouse sort of "glide" from point A to point B at a seemingly natural pace, so here's my solution:

import time
import win32api

MOUSE_SPEED = .4 #seconds

def mouse_glide_to(x,y):
    """Smooth glides mouse from current position to point x,y with default timing and speed"""
    x1,y1 = win32api.GetCursorPos()
    smooth_glide_mouse(x1,y1, x, y, MOUSE_SPEED)

def smooth_glide_mouse(x1,y1,x2,y2, t, intervals):
    """Smoothly glides mouse from x1,y1, to x2,y2 in time t using intervals amount of intervals"""
    distance_x = x2-x1
    distance_y = y2-y1
    for n in range(0, intervals+1):
        move_mouse(x1 + n * (distance_x/intervals), y1 + n * (distance_y/intervals))

def move_mouse(x, y):
mouse_glide_to(x,y) will move the cursor from its current position to point (x,y) in MOUSE_SPEED seconds. It works perfectly!


  1. Have you considered using Bezier curves with random jitter to simulate more natural movement?