2016-04-21 28 views
1

我在使該功能正常工作時遇到問題。我必須創建一個充當出租車映射器的Winform應用程序。在加載時,出租車根據文本文件放置在相同的位置。當用戶點擊表格時,最近的出租車應該移動到「用戶」或位置,然後停車。根據winform中的鼠標單擊找到最短距離的對象

除了最近的出租車並不總是去的位置,一切工作正常。更遠的出租車將轉到該位置。它似乎在某些時候有效,但並非全部。我不知道如果我的邏輯是在Form1_MouseDown功能

private void Form1_MouseDown(object sender, MouseEventArgs e) 
{ 
    if (pickUp) //Are we picking up a passenger? 
    { 
     //Convert mouse pointer location to local window locations 
     int mLocalX = this.PointToClient(Cursor.Position).X; 
     int mLocalY = this.PointToClient(Cursor.Position).Y; 

     //set the minimum value (for range finding) 
     int min = int.MaxValue; 
     //Temporary object to get the handle for the taxi object we want to manipulate 
     taxiCabTmp = new TaxiClass(); 

     //Iterate through each object to determine who is the closest 
     foreach (TaxiClass taxiCab in taxi) 
     { 
      if (Math.Abs(Math.Abs(taxiCab.CabLocationX - mLocalX) + Math.Abs(taxiCab.CabLocationY - mLocalY)) <= min) 
      { 
       min = Math.Abs(Math.Abs(taxiCab.CabLocationX - mLocalX) + Math.Abs(taxiCab.CabLocationY - mLocalY)); 
       //We found a minimum, grab a handle to the object's instance 
       taxiCab.GetReference(ref taxiCabTmp); 
      } 
     } 
     //Call the propogate method so it can spin off a thread to slowly change it's location for the timer to also change 
     taxiCabTmp.Propogate(mLocalX - 20, mLocalY - 20); 
     taxiCabTmp.occupied = true; //This taxi object is occupied 
     pickUp = false; //We are not picking up a passenger at the moment 
    } 
    else //We are dropping off a passenger 
    { 
     taxiCabTmp.Propogate(this.PointToClient(Cursor.Position).X, this.PointToClient(Cursor.Position).Y); 
     taxiCabTmp.occupied = false; 
     pickUp = true; //We can pick up a passenger again! 
    } 
} 

回答

2

使用此公式計算兩個座標之間的距離。

var distance = Math.Sqrt(Math.Pow(taxiCab.CabLocationX - mLocalX, 2) + Math.Pow(taxiCab.CabLocationY - mLocalY, 2)); 
if (distance <= min) { 
    min = distance; 
    //We found a minimum, grab a handle to the object's instance 
    taxiCab.GetReference(ref taxiCabTmp); 
} 
3

你是正確的,你用於確定距離的計算並不總是正確無誤。一個角度的物體會計算得比實際距離更遠。

看一看這個鏈接瞭解更多信息:http://www.purplemath.com/modules/distform.htm

下面是一個例子:

int mLocalX = 1; 
int mLocalY = 1; 
int taxiCab.CabLocationX = 2; 
int taxiCab.CabLocationY = 2; 

double distance = Math.Sqrt(Math.Pow((taxiCab.CabLocationX - mLocalX), 2) + Math.Pow((taxiCab.CabLocationY - mLocalY), 2)); 

正如一個側面說明,你應該不是你的類與類追加,即TaxiClass,它應該簡單地稱爲出租車。