简体   繁体   English

沿对角线移动鼠标

[英]Moving the mouse along a diagonal line

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'. 例如,如果我给它设置animateMouseDiag(100,300),它将使鼠标向右移动100,向下移动300,但是沿对角线而不是“ 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. 同样,如果我给它(-50,-200),它将沿对角线路径移动到那些相对坐标(向左50和向上200)。

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. 它们似乎偏向屏幕左上方。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM