R – How to “snap” a directional (2D) vector to a compass (N, NE, E, SE, S, SW, W, NW)

algorithmmathtrigonometryvector

I have a bunch of vectors normal to window surfaces in a 3D modelling software. Projected to the XY-Plane, I would like to know in which direction they are facing, translated to the 8 compass coordinates (North, North-East, East, South-East, South, South-West, West and North-West).

The vectors work like this:

  • the X axis represents East-West (with East being positive)
  • the y axis represents North-South (with North being positive)
  • thus
    • (0, 1) == North
    • (1, 0) == East
    • (0,-1) == South
    • (-1,0) == West

Given a vector (x, y) I am looking for the closest of the 8 compass coordinates. Any ideas on how to do this elegantly?

Best Answer

This works in Java, computing a value 0...7 for the eight directions:

import static java.lang.Math.*;    

int compass = (((int) round(atan2(y, x) / (2 * PI / 8))) + 8) % 8;

The result maps to the compass as follows:

0 => E
1 => NE
2 => N
3 => NW
4 => W
5 => SW
6 => S
7 => SE
Related Topic