898Matthew - 7 months ago 23

Java Question

I'm trying to move a cursor in a sin wave pattern but because the mouseMove function takes integers as parameters I can only move the mouse to coordinates on the wave where both the x and y values are integers. This is not a problem when the "height" of the wave is smaller but as it gets larger you can see the gaps more easily since the distance between two coordinates that have x and y values that are integers is larger. Is there a way that I can move the cursor to coordinates that are close to these non integer coordinates so that it will look like a complete wave?

`import java.awt.Robot;`

public class WaveMotion {

public static void MoveMouseWave(int startX, int startY, int waveHeight, int waveLength, int speed) {

int a = 0;

while(a < waveLength) {

int x = (a * waveHeight) + startX;

int y = (int) ((Math.sin(a) * waveHeight) + startY);

System.out.println(x + "," + y);

a++;

try{

Robot robot = new Robot();

robot.delay(((speed * -1) + 10) * 100);

robot.mouseMove(x, y);

}

catch(Exception e) {}

}

}

}

Answer

The fact that `mouseMove`

takes integer parameters does not require you to use integers for the entire calculation. For example, it is not necessary to only pass integers to `Math.sin`

, and in fact these will be converted to doubles anyway. You can use `double`

s or `float`

s for your intermediate calculations and then cast to `int`

when computing the final value.

One other reason that your cursor will appear to be jumping from point to point isn't directly related to the fact that the co-ordinates are integers, but because you are stepping along x by a value equal to the `waveHeight`

each time, which is a larger jump than the integer limitation imposes:

```
int x = (a * waveHeight) + startX;
```

Alternatively, you can step x by 1 each time (so no big jumps), and divide by `waveHeight`

when calling `sin()`

to reflect the fact that you have moved a smaller step along the wave:

```
int x = a + startX;
int y = (int)(Math.sin((double)a / (double)waveHeight) * (double)waveHeight) + startY;
```

Be careful to check for a `waveHeight`

of zero to avoid division by zero errors. You could also change the type of `waveHeight`

to `double`

to avoid having to cast it. Because you are stepping a smaller distance each time, you will need to increase `waveLength`

by a factor of `waveHeight`

to get a wave of the same length.