Created
March 6, 2017 21:03
-
-
Save hpohlmeyer/a775bf4963ac2d68b27cec347d2854c5 to your computer and use it in GitHub Desktop.
Point calculation helper functions
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
// ============================================================================= | |
// POINT CALCULATION HELPER FUNCTIONS | |
// | |
// This is a collection of various mathematical helper functions, for manipula- | |
// ting points and measuring angles and distances. | |
// | |
// Inside a function, no other function form the list is used, to ensure you can | |
// use the indipendently. | |
// ============================================================================= | |
/** | |
* Get the distance between two points | |
* | |
* @param {Object} p1 Point A – {x: Int, y: Int} | |
* @param {Object} p2 Point B – {x: Int, y: Int} | |
* @return {Number} The distance between `p1` and `p2`. | |
*/ | |
const distance = (p1, p2) => { | |
const dx = p1.x - p2.x, | |
dy = p1.y - p2.y; | |
return Math.sqrt(dx * dx + dy * dy); | |
}; | |
/** | |
* The angle between two points in radians. | |
* | |
* @param {Object} p1 Point A – {x: Int, y: Int} | |
* @param {Object} p2 Point B – {x: Int, y: Int} | |
* @return {Number} The angle between `p1` and `p2` in radians. | |
*/ | |
const angleInRadians = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x); | |
/** | |
* The angle between two points in radians. | |
* | |
* @param {Object} p1 Point A – {x: Int, y: Int} | |
* @param {Object} p2 Point B – {x: Int, y: Int} | |
* @return {Number} The angle between `p1` and `p2` in radians. | |
*/ | |
const angleInDegrees = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI; | |
/** | |
* Convert degrees to radians. | |
* | |
* @param {Number} degrees An angle in degrees | |
* @return {Number} The angle in radians | |
*/ | |
const degreesToRadians = degrees => degrees * Math.PI / 180; | |
/** | |
* Convert radians to degreess. | |
* | |
* @param {Number} radians An angle in radians | |
* @return {Number} The angle in degrees | |
*/ | |
const radiansToDegrees = radians => radians * 180 / Math.PI; | |
/** | |
* Move `point` by `distance` in a direction defined by `angle`. | |
* | |
* @param {Object} point The point, that shall be moved. | |
* @param {Number} distance The distance, the point will be moved. | |
* @param {Number} angle The direction __in radians__, the point will be | |
* moved in. | |
*/ | |
const movePoint = (point, distance, angle) => { | |
point.x += distance * Math.cos(angle); | |
point.y += distance * Math.sin(angle); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment