2016-01-26 79 views
1

其實我試圖做一個程序,告訴你是否在我的祕密半徑內。 我會設置一個點,例如x = 1000和y = 400,我會設置半徑爲例如50,如果我的光標在距離點50的半徑上,它會寫入控制檯「你在半徑內,x是1000,y是400」。檢查光標是否在一定範圍內

這不是一個家庭作業或類似的東西,我只是在嘗試新的東西。

好吧,所以這裏是我試過的,不能再移動了。

- 注意:半徑應該是圓形,所以我想我需要實現[RPI但我不太確定如何做到這一點編程:

class Program 
{ 
    [DllImport("user32.dll", SetLastError = true)] 
    public static extern bool GetCursorPos(out System.Drawing.Point point); 

    [DllImport("user32.dll")] 
    public static extern int GetAsyncKeyState(System.Windows.Forms.Keys vKey); 

    static void Main(string[] args){ 
     Point cursorPoint; 
     Point myPos = Point.Empty; 
     myPos.X = 1000; 
     myPos.Y = 400; 
     int myRadius = 50; 
     while (true){ 
      //if pressed ESC let me end the program. 
      if (GetAsyncKeyState(Keys.Escape) > 0) 
       return; 
      //get cursor pos and store it in cursorPoint 
      GetCursorPos(out cursorPoint); 

      //here should be a check with some calculation about radius, but I can't do that.. 
      Console.WriteLine("You are in radius and your cursor coordinations are X:{0}|Y:{1}",cursorPoint.X,cursorPoint.Y); 
      //help cpu 
      Thread.Sleep(16); 
     } 

    } 
} 

感謝您的幫助。

+0

這是一個數學問題。距離= sqrt [(x2-x1)^ 2 +(y2-y1)^ 2] – Szer

+0

這是一個winforms還是wpf項目? – mike

+0

以winforms作爲參考的控制檯應用程序 –

回答

0

你只需要使用畢達哥拉斯來計算點之間的距離,並將其與範圍進行比較。

通常情況下,您需要平方根來找出兩點之間的距離,但是如果您只需要與範圍進行比較,就可以對範圍進行平方,避免採用平方根。

例如:

static bool isInRange(Point p1, Point p2, int range) 
{ 
    int rangeSquared = range * range; 

    int deltaX = p2.X - p1.X; 
    int deltaY = p2.Y - p1.Y; 

    int distanceSquared = deltaX*deltaX + deltaY*deltaY; 

    return distanceSquared <= rangeSquared; 
} 

還要注意,如果座標變得過於龐大,這些計算將溢出,但這是不會發生的用於在屏幕上像素COORDS。

+0

謝謝,我會完全試驗它。哦,還有,它應該是'int deltaY = p2.Y - p1.Y'? –

+0

@dadasdasdas是的,它應該,並感謝德米特里糾正錯字。 –

0

正如我所理解的你的問題是關於確定兩個點之間的直線距離,即圍繞其中心的圓的半徑。

爲此,您首先需要x和y中的增量。之後,你使用畢達哥拉斯定理(找到here)。

double deltaX = myPos.X - cursorPoint.X; 
double deltaY = myPos.Y - cursorPoint.Y; 
double distance = Math.Sqrt(Math.Pow(deltaX, 2) + Math.Pow(deltaY, 2)); 
// Continue with your calculations with distance and myRadius 
相關問題