4

The Java Robot class allows one to move the mouse as if the actual physical mouse was moved.

However, how does one move the mouse from Point1 to Point2 in a humane (and thus not instant) manner? Aka, how does one set the speed of movement?

If no such speed is possible with the Robot class, thus if the mouse can only be moved instantenously, what kind of "algorithm" should be used to mimic a human's mouse movement? Should it move the mouse pixel by pixel with a certain incrementing speed?

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Tom
  • 8,536
  • 31
  • 133
  • 232

3 Answers3

6

Here is a pretty good way here:

Consider start_x where your mouse starts and end_x where you are wanting it to end. Same for y

for (int i=0; i<100; i++){  
    int mov_x = ((end_x * i)/100) + (start_x*(100-i)/100);
    int mov_y = ((end_y * i)/100) + (start_y*(100-i)/100);
    robot.mouseMove(mov_x,mov_y);
    robot.delay(10);
}

Hope that helps...

forsvarir
  • 10,749
  • 6
  • 46
  • 77
Geoff
  • 61
  • 1
  • 2
  • 2
    Moving the division out of the parentheses makes it a bit faster and also more precise. The above algorithm written as is moves from (1, 1) to (1, 1) through (0, 0). One more problem: It only goes 99% of the way. – maaartinus Nov 03 '11 at 23:09
  • delay function is no longer available..the answer need to be updated – Abdulmalek Dery Aug 25 '21 at 05:20
1

The Robot class has a delay(...) method that you can use to control movement from point to point. Try a few different alogorithms to determine what you like.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    The delay method sleeps the robot. How would this slow down the movement of the mouse? Or are you implying that I should create my own algorithm that moves the mouse pixel by pixel with a certain increment? – Tom Mar 17 '11 at 15:35
  • Yes you need to create a loop that moves the mouse a pixel (or two) and then delays before moving to the next pixel. That is why you can create your own algorithm. You determine how many pixels to move and how long to delay etc. – camickr Mar 17 '11 at 16:21
  • that does not answer what kind of algorithm would be humane though. – Tom Mar 17 '11 at 20:35
  • What you expect us to do everything? I'm not an expert on what would be "humane". Thats why I suggested you try a couple of algorithms yourself to see what you like :) If you want you can even post code thats lets people try your code with the different algorithms and people can vote on what they like. – camickr Mar 17 '11 at 20:57
0

Rewrite Geoff's answer for easier understanding:

for (int i=0; i<=100; i++){
   int mov_x = start_x + (end_x - start_x) * i/100;
   int mov_y = start_y + (end_y - start_y) * i/100;
   robot.mouseMove(mov_x,mov_y);
   robot.delay(10);
}
Reins
  • 1,109
  • 1
  • 17
  • 35
hthhth
  • 111
  • 1
  • 5