Skip to content

Instantly share code, notes, and snippets.

@N8python
Created March 13, 2020 01:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save N8python/2e30b9c7f79e576c3691f85570132efd to your computer and use it in GitHub Desktop.
Save N8python/2e30b9c7f79e576c3691f85570132efd to your computer and use it in GitHub Desktop.
The following code calculates a unit vector from coordinates (x, y) to the point (x1, y1).
const degrees = radians => radians * 180 / Math.PI;
const radians = degrees => degrees * Math.PI / 180;
function vecTo(x1, y1, x2, y2) {
const xDist = x2 - x1;
const yDist = y2 - y1;
let direction;
if (xDist > 0 && yDist > 0) {
direction = degrees(Math.atan(yDist / xDist));
} else if (xDist > 0 && yDist < 0) {
direction = 360 + degrees(Math.atan(yDist / xDist));
} else {
direction = 180 + degrees(Math.atan(yDist / xDist));
}
return [Math.cos(radians(direction)), Math.sin(radians(direction))];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment