Created
March 13, 2020 01:04
-
-
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).
This file contains hidden or 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
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