Skip to content

Instantly share code, notes, and snippets.

@afreeland
Last active December 10, 2015 19:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save afreeland/4484102 to your computer and use it in GitHub Desktop.
Save afreeland/4484102 to your computer and use it in GitHub Desktop.
JavaScript: Get Angle By Two Vectors On Coordinate Plan
/**
* Defines an x,y coordinate
* @param {float} x coordinate
* @param {float} y coordinate
*/
function Point (x, y) {
this.x = x;
this.y = y;
}
/**
* Get angle by two vectors on a coordinate plan
* This works regardless of origin
* @param {Point} P2 x, y
* @param {Point} P1 x, y --This can be thought of as the new origin point
* @param {bool} UseRadians [The default is degrees, however to return radians pass in true]
*/
function AngleByVectors (P1, P2, UseRadians) {
var DeltaY = P2.y - P1.y,
DeltaX = P2.x - P1.x;
return !UseRadians ? Math.atan2(DeltaY, DeltaX) * 180/Math.PI : Math.atan2(DeltaY, DeltaX);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment