2012-08-01 122 views
0

我可以使用什麼樣的數學算法來計算移動鼠標的路徑?我只是想有這種類型的函數:沿對角線移動鼠標

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

例如,如果我給它animateMouseDiag(100,300),將鼠標100移動到右側和300下降,但對角,不是右,則─在'L'下。同樣,如果我給它(-50,-200),它會將它移動到對角線路徑上的相對座標(50左和200上)。

謝謝! (順便說一句,這是一個ALT帳戶,因爲我覺得自己像一個白癡問我的主要基本高中數學,我只是不能把它翻譯成編程。)

編輯:我想出了這個:

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)); 
      } 
     } 

這是Bresenham's line algorithm。奇怪的是,這些線條並沒有畫出一個設定的角度。他們似乎被吸引到屏幕的左上角。

回答

1

將位置座標存儲爲浮點值,然後可以將方向表示爲單位矢量並乘以特定速度。

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

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

heh。在那個上畫一個空白......編輯:我明白了! – user1567298 2012-08-01 01:29:35