Moving the mouse along a diagonal line

冷暖自知 提交于 2020-01-14 06:52:27

问题


What kind of math algorithm could I use to calculate the path to move a mouse? I simply want to have this type of function:

animateMouseDiag(int X, int Y){
    //Move mouse 1 step towards goal, for loop most likely, from the current Mouse.Position
    Thread.Sleep(1);
}

For example, if I give it animateMouseDiag(100,300), it would move the mouse 100 to the right and 300 down, but diagonally, not right-then-down in an 'L'. Similarly, if I gave it (-50,-200) it would move it to those relative coordinates (50 left and 200 up) along the diagonal path.

Thank you! (By the way, this is an alt account since I feel like an idiot asking about basic high school math on my main. I just can't translate it into programming.)

EDIT: I have come up with this:

public static void animateCursorTo(int toX, int toY)
        {
            double x0 = Cursor.Position.X;
            double y0 = Cursor.Position.Y;

            double dx = Math.Abs(toX-x0);
            double dy = Math.Abs(toY-y0);

            double sx, sy, err, e2;

            if (x0 < toX) sx = 1;
            else sx = -1;
            if (y0 < toY) sy = 1;
            else sy = -1;
            err = dx-dy;

            for(int i=0; i < toX; i++){
                //setPixel(x0,y0)
                e2 = 2*err;
                if (e2 > -dy) {
                    err = err - dy;
                    x0 = x0 + sx;
                }
                if (e2 <  dx) {
                    err = err + dx;
                    y0 = y0 + sy;
                }
                Cursor.Position = new Point(Convert.ToInt32(x0),Convert.ToInt32(y0));
            }
        }

This is Bresenham's line algorithm. Strangely though, the lines don't draw on a set angle. They seem to be gravitating towards the top left of the screen.


回答1:


Store the position coordinates as floating point values, then you can represent the direction as a unit vector and multiply by a specific speed.

double mag = Math.Sqrt(directionX * directionX  + directionY * directionY);

mouseX += (directionX / mag) * speed;
mouseY += (directionY / mag) * speed;


来源:https://stackoverflow.com/questions/11751370/moving-the-mouse-along-a-diagonal-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!