2012-02-18 103 views
0

那麼我如何才能從特定距離獲得某個點的x,y座標?如何從特定距離獲得x,y座標

所以

public static Location2D DistanceToXY(Location2D current, Directions dir, int steps) { 
      ushort x = current.X; 
      ushort y = current.Y; 

      for (int i = 0; i < steps; i++) { 
       switch (dir) { 
        case Directions.North: 
         y--; 
         break; 
        case Directions.South: 
         y++; 
         break; 
        case Directions.East: 
         x++; 
         break; 
        case Directions.West: 
         x--; 
         break; 
        case Directions.NorthWest: 
         x--; 
         y--; 
         break; 
        case Directions.SouthWest: 
         x--; 
         y++; 
         break; 
        case Directions.NorthEast: 
         x++; 
         y--; 
         break; 
        case Directions.SouthEast: 
         x++; 
         x++; 
         break; 
       } 
      } 
      return new Location2D(x, y); 
     } 

就是我在這裏做什麼是正確的?

+6

取決於在你走什麼方向 – 2012-02-18 06:11:12

+0

難道這取決於你在行進的方向? – Oleksi 2012-02-18 06:11:31

+0

你的意思是哪些地點可以使用?如果是這樣,你可以遞歸地做。 – Ovilia 2012-02-18 06:19:20

回答

0

我假設你正在尋找一個通用的解決方案。正如其他人指出的那樣,你需要一個方向作爲缺失的輸入。您將基本上使用方向和大小(在這種情況下爲10),並將這些極座標轉換爲笛卡爾座標。然後將所得的座標加在一起X + Xoffset = Xnew,Y + Yoffset = Ynew。

轉換的細節在這裏: http://www.mathsisfun.com/polar-cartesian-coordinates.html

編輯:在您貼出你的代碼,答案是否定的。 NorthWest,SouthWest,NorthEast,SouthEast的情況並不正確。在這些情況下,您將移動1.41(aprox)像素。你不應該試圖逐步解決這個難題。使用極座標數學計算總和偏移量,然後四捨五入到最接近的整數。

繼承人簡化僞國防部爲您的解決方案:

public static Location2D DistanceToXY(Location2D current, Directions dir, int steps) { 
     ushort x = current.X; 
     ushort y = current.Y; 

     switch (dir) { 
      case Directions.North: 
       y=y+steps; 
       break; 
      case Directions.South: 
       y=y-steps; 
       break; 
      case Directions.East: 
       x=x+steps; 
       break; 
      case Directions.West: 
       x=x-steps; 
       break; 
      case Directions.NorthWest: 
       float sqrt2 = 2^0.5 
       x=x+int((sqrt2 * steps) + 0.5); 
       y=y-int((sqrt2 * steps) + 0.5); 
       break; 
      case Directions.SouthWest: 
       x=x-int((sqrt2 * steps) + 0.5); 
       y=y-int((sqrt2 * steps) + 0.5); 
       break; 
      case Directions.NorthEast: 
       x=x+int((sqrt2 * steps) + 0.5); 
       y=y+int((sqrt2 * steps) + 0.5); 
       break; 
      case Directions.SouthEast: 
       x=x-int((sqrt2 * steps) + 0.5); 
       y=y+int((sqrt2 * steps) + 0.5); 
       break; 
     } 
     return new Location2D(x, y); 
    } 
+0

thnx求助^ _ ^ – Abanoub 2012-02-18 07:02:41