两个坐标的相对基数方向

JCa*_*ter 6 c# algorithm

以下枚举定义如下:

public enum Direction
{
    North,
    South,
    East,
    West,
    Northeast,
    Northwest,
    Southeast,
    Southwest,
    Undefined
}
Run Code Online (Sandbox Code Playgroud)

给定二维空间中的两组坐标,我想确定从第2点到第1点的相对基数方向.

例子:

  • P1(1,1)和P2(0,1)返回Direction.North,因为P2是P1的北部
  • P1(1,1)和P2(5,4)返回Direction.Southeast
  • P1(1,1)和P2(1,1)返回Direction.Undefined

我目前的方法涉及一系列条件,即

if (P1.X == P2.X)
{
    // either North, South or Undefined
    if (P1.Y < P2.Y)
        return Direction.South;
    else if (P1.Y > P2.Y)
        return Direction.North,
    else
        return Direction.Undefined;
}
else if (P1.Y == P2.Y)
{
    ...
}
else 
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我正在寻求更短,更优雅的解决方案.

rom*_*oza 5

我3美分 - 我在等待改进

这是枚举:

public enum Direction
{
    North = 0,
    South = 4,
    East = 6,
    West = 2,
    Northeast = 7,
    Northwest = 1,
    Southeast = 5,
    Southwest = 3,
    Undefined = -1
}
Run Code Online (Sandbox Code Playgroud)

转换如下:

public static Direction GetDirection(Point p1, Point p2) {
    double angle = Math.Atan2(p2.Y - p1.Y, p2.X - p1.X);
    angle += Math.PI;
    angle /= Math.PI / 4;
    int halfQuarter = Convert.ToInt32(angle);
    halfQuarter %= 8;
    return (Direction)halfQuarter;
}
Run Code Online (Sandbox Code Playgroud)

Direction.Undefined然而,它不会返回,因为

如果y为0且x为0,则θ= 0.

(来自https://msdn.microsoft.com/library/system.math.atan2(v=vs.110).aspx)