本文介绍了两个坐标的相对基本方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

定义了以下枚举:

public enum Direction
{
    North,
    South,
    East,
    West,
    Northeast,
    Northwest,
    Southeast,
    Southwest,
    Undefined
}

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

Given two sets of coordinates in two-dimensional space, I'd like to determine the relative cardinal direction from Point 2 to 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

我当前的方法涉及很多条件,即

My current approach involves a bunch of conditions, i.e.

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
{
    ...
}

我正在寻找一个更短,更优雅的解决方案.

I'm seeking a shorter and more elegant solution.

推荐答案

我的3美分-我正在等待改善

My 3 cents - i'm waiting for improvements

这是枚举:

public enum Direction
{
    North = 0,
    South = 4,
    East = 6,
    West = 2,
    Northeast = 7,
    Northwest = 1,
    Southeast = 5,
    Southwest = 3,
    Undefined = -1
}

转换为:

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;
}

但是它不会返回Direction.Undefined,因为

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

这篇关于两个坐标的相对基本方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 17:34