Following enum is defined:
public enum Direction
{
North,
South,
East,
West,
Northeast,
Northwest,
Southeast,
Southwest,
Undefined
}
Given two sets of coordinates in two-dimensional space, I'd like to determine the relative cardinal direction from Point 2 to 1.
Examples:
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.
North, east, south, and west are the four cardinal directions, often marked by the initials N, E, S, and W. East and west are at right angles to north and south. East is in the clockwise direction of rotation from north. West is directly opposite east.
The four cardinal directions, or cardinal points, are the four main compass directions: north, east, south, and west, commonly denoted by their initials N, E, S, and W respectively. Relative to north, the directions east, south, and west are at 90 degree intervals in the clockwise direction.
A compass rose with both ordinal and cardinal directions will have eight points: N, NE, E, SE, S, SW, W, and NW.
Cardinal directions are one set of directions that people around the world use. The four cardinal directions are north, south, east and west. These directions use the rising and setting of the sun as reference points. Because the Earth rotates from west to east, the sun appears to rise in the east and set in the west.
My 3 cents - i'm waiting for improvements
Here is the enum:
public enum Direction
{
North = 0,
South = 4,
East = 6,
West = 2,
Northeast = 7,
Northwest = 1,
Southeast = 5,
Southwest = 3,
Undefined = -1
}
and the conversion goes as:
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;
}
It does not return Direction.Undefined
however, because
if y is 0 and x is 0, θ = 0.
(from https://msdn.microsoft.com/library/system.math.atan2(v=vs.110).aspx)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With