Algorithm for moving the 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 I can use that 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 the screen without animation. Now my task is to move the mouse to this coordinate, but it should also show the mouse, moving one pixel at a time. I need to create a loop that moves the mouse cursor a few pixels x and y at a time, so this is what I thought:

 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 the correct x2 and y2 values ​​so that the mouse moves in a straight line and finally reaches x and y. Can someone help me.

+4
source share
4 answers

Below is the code for this. This code uses the Bresenham Line Algo. For more information on soln try http://en.wikipedia.org/wiki/Bresenham's_line_algorithm if you are looking for no jagged lines

  boolean steep = Math.abs(y1 - y0) > Math.abs(x1 - x0); if (steep) { int t; // swap(x0, y0); t = x0; x0 = y0; y0 = t; // swap(x1, y1); t = x1; x1 = y1; y1 = t; } if (x0 > x1) { int t; // swap(x0, x1); t = x0; x0 = x1; x1 = t; // swap(y0, y1); t = y0; y0 = y1; y1 = t; } int deltax = x1 - x0; int deltay = Math.abs(y1 - y0); int error = deltax / 2; int ystep; int y = y0; if (y0 < y1) ystep = 1; else ystep = -1; for (int x = x0; x < x1; x++) { if (steep) moveMouse(y, x); else moveMouse(x, y); error = error - deltay; if (error < 0) { y = y + ystep; error = error + deltax; } } 
+5
source

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

Illustration of Bresenham's line algorithm

+9
source

The problem you are trying to solve is linear interpolation, since you have a linear function - a line between the start point (x0, y0) and the end point (x1, y1).

Fortunately, the solution is simple. The Wikipedia article gives examples of almost what you are trying to do.

http://en.wikipedia.org/wiki/Linear_interpolation

+3
source

You could interpolate a straight line .... basically by laying y = mx + b at given points.

+2
source

Source: https://habr.com/ru/post/1389743/


All Articles