Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to move mouse from one point to another in a straight line

I am trying to make a small program that will move the mouse from the current position to the given position. Here is a method that i can use which will move the mouse from one point to another but without animation:

moveMouse(int x, int y);

This will move the mouse from the current coordinates to x,y on screen without animation. Now my job is to move the mouse to that coordinate, but it should also show the mouse moving one pixel at a time. I need to create a loop which moves the mouse cursor few pixels x and y at a time so that Here is what i have been thinking:

public void moveMouseAnimation(x,y){
      //Integers x2 and y2 will be the current position of the mouse cursor
      boolean isRunning = true;
      while(isRunning){
           delay(10); // <- 10 Milliseconds pause so that people can see the animation
           x2 -= 1;
           y2 -= 1;
           moveMouse(x2,y2);
           if(x2 == x && y2 == y) isRunning = false; //Ends loop
      }
}

Now i need to find correct x2 and y2 values so that the mouse moves in a straight line and reaches x and y at last. Could someone help me.

like image 658
KSubedi Avatar asked Nov 30 '22 06:11

KSubedi


1 Answers

You want the Bresenham's line algorithm. It is commonly used to draw a line between two points, but you, instead of drawing a line, will move the mouse along it.

Illustration of Bresenham's line algorithm

like image 72
Sergio Tulentsev Avatar answered Dec 04 '22 12:12

Sergio Tulentsev