該解決方案將正確地返回您Direction.Undefined
當座標不沿一個方向恰好指向來計算,它僅通過檢查角(消除嵌套的後續控制語句see unit circle)。請注意,我認爲點類型的X
和Y
屬性定義爲int
,但即使將它們定義爲浮點類型值(例如float,decimal或double),也應該可以正常工作。
static Direction GetDirection(Point p1, Point p2)
{
double rad = Math.Atan2(p2.Y - p1.Y, p2.X - p1.X);
// Ajust result to be between 0 to 2*Pi
if (rad < 0)
rad = rad + (2 * Math.PI);
var deg = rad * (180/Math.PI);
if (deg == 0)
return Direction.East;
else if (deg == 45)
return Direction.Northeast;
else if (deg == 90)
return Direction.North;
else if (deg == 135)
return Direction.Northwest;
else if (deg == 180)
return Direction.West;
else if (deg == 225)
return Direction.Southwest;
else if (deg == 270)
return Direction.South;
else if (deg == 315)
return Direction.Southeast;
else
return Direction.Undefined;
}
一個簡單的測試......
Direction dir;
dir = GetDirection(new Point(0, 0), new Point(1, 0));
Console.WriteLine(dir);
dir = GetDirection(new Point(0, 0), new Point(1, 1));
Console.WriteLine(dir);
dir = GetDirection(new Point(0, 0), new Point(0, 1));
Console.WriteLine(dir);
dir = GetDirection(new Point(0, 0), new Point(-1, 1));
Console.WriteLine(dir);
dir = GetDirection(new Point(0, 0), new Point(-1, 0));
Console.WriteLine(dir);
dir = GetDirection(new Point(0, 0), new Point(-1, -1));
Console.WriteLine(dir);
dir = GetDirection(new Point(0, 0), new Point(0, -1));
Console.WriteLine(dir);
dir = GetDirection(new Point(0, 0), new Point(1, -1));
Console.WriteLine(dir);
輸出...
East
Northeast
North
Northwest
West
Southwest
South
Southeast
注意,如果Point
類型定義X
和Y
性質爲浮點類型,然後像以下將返回Direction.Undefined
,因爲它不是完全指向東方,所以希望這適合您的意圖...
// "Almost" pointing east...
dir = GetDirection(new Point(0, 0), new Point(1, 0.001));
輸出...
Undefined
使用矢量的角度'P2 - P1'(使用'arctan2() '),然後做'if(-15°<= angle <= 15°)返回Direction.North'? (即在numDirections切片中分割整個事物,然後檢查角度是否在一個區間內)。我也不明白爲什麼如果'P1.X
它是以標準笛卡爾座標定義的嗎?如果是這樣,那麼第一個樣本不應該是Direction.West,而第二個Direction.Northeast? – PiotrWolkowski
@PiotrWolkowski顯然,OP沿着負X軸取向爲北,而不是通常的正Y軸。這很奇怪,但是「標準笛卡爾座標」中沒有任何規定北方的方向。 – RBarryYoung