Last active
November 14, 2022 17:44
-
-
Save basarat/4670200 to your computer and use it in GitHub Desktop.
Snapping an angle to the nearest cardinal direction in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Given "0-360" returns the nearest cardinal direction "N/NE/E/SE/S/SW/W/NW" | |
*/ | |
export function getCardinal(angle) { | |
/** | |
* Customize by changing the number of directions you have | |
* We have 8 | |
*/ | |
const degreePerDirection = 360 / 8; | |
/** | |
* Offset the angle by half of the degrees per direction | |
* Example: in 4 direction system North (320-45) becomes (0-90) | |
*/ | |
const offsetAngle = angle + degreePerDirection / 2; | |
return (offsetAngle >= 0 * degreePerDirection && offsetAngle < 1 * degreePerDirection) ? "N" | |
: (offsetAngle >= 1 * degreePerDirection && offsetAngle < 2 * degreePerDirection) ? "NE" | |
: (offsetAngle >= 2 * degreePerDirection && offsetAngle < 3 * degreePerDirection) ? "E" | |
: (offsetAngle >= 3 * degreePerDirection && offsetAngle < 4 * degreePerDirection) ? "SE" | |
: (offsetAngle >= 4 * degreePerDirection && offsetAngle < 5 * degreePerDirection) ? "S" | |
: (offsetAngle >= 5 * degreePerDirection && offsetAngle < 6 * degreePerDirection) ? "SW" | |
: (offsetAngle >= 6 * degreePerDirection && offsetAngle < 7 * degreePerDirection) ? "W" | |
: "NW"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@basarat can you please help me. I am taking only directions 4 so I will divide degree/4 is it's correct?