Last active
January 17, 2018 11:34
-
-
Save RonenNess/bc738bc9c06369842c1a50d4a7f39fc7 to your computer and use it in GitHub Desktop.
Some useful math utils for nodejs.
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
/** | |
* Provide extended math utilities. | |
* | |
* Author: Ronen Ness. | |
* Since: 2017. | |
*/ | |
"use strict"; | |
/** | |
* Provide extended math utilities. | |
*/ | |
var MathX = { | |
// pi * 2 | |
PI2: Math.PI * 2, | |
/** | |
* Convert degrees to radians. | |
*/ | |
toRadians: function(degrees) { | |
return degrees * Math.PI / 180; | |
}, | |
/** | |
* Convert radians to degrees. | |
*/ | |
toDegrees: function(radians) { | |
return radians * 180 / Math.PI; | |
}, | |
/** | |
* Lerp between two vectors. | |
* Note: v1 must have clone() function. | |
*/ | |
lerpVectors: function(v1, v2, alpha) | |
{ | |
var ret = v1.clone(); | |
ret.x += (v2.x - ret.x) * alpha; | |
ret.y += (v2.y - ret.y) * alpha; | |
return ret; | |
}, | |
/** | |
* Find shortest distance between two given radian angles. | |
*/ | |
radiansDistance: function(a0, a1) | |
{ | |
var max = Math.PI * 2; | |
var da = (a1 - a0) % max; | |
return 2 * da % max - da; | |
}, | |
/** | |
* Lerp between two radian angles. | |
*/ | |
lerpRadians: function(a0, a1, alpha) | |
{ | |
return a0 + this.radiansDistance(a0, a1) * alpha; | |
}, | |
/** | |
* Lerp between two degrees. | |
*/ | |
lerpDegrees: function(a0, a1, alpha) | |
{ | |
// convert to radians | |
a0 = this.toRadians(a0); | |
a1 = this.toRadians(a1); | |
// lerp | |
var ret = this.lerpRadians(a0, a1, alpha); | |
// convert back to degree and return | |
return this.toDegrees(ret); | |
}, | |
/** | |
* Lerp between two numbers. | |
*/ | |
lerp: function(x, y, alpha) { | |
return x + (y - x) * alpha; | |
}, | |
/** | |
* Round numbers from 10'th digit. | |
* This is useful for calculations that should return round or almost round numbers, but have a long tail of 0's and 1 due to floating points accuracy. | |
*/ | |
smartRound: function(num) | |
{ | |
return Math.round(num * 100000000.0) / 100000000.0; | |
}, | |
/** | |
* Return distance between two points. | |
*/ | |
distance: function(p1, p2) { | |
var dx = p2.x - p1.x, | |
dy = p2.y - p1.y; | |
return Math.sqrt(dx * dx + dy * dy); | |
}, | |
/** | |
* Return angle (in radians) between two points. | |
*/ | |
angleBetween: function(P1, P2, wrap) { | |
var deltaY = P2.y - P1.y, | |
deltaX = P2.x - P1.x; | |
var ret = Math.atan2(deltaY, deltaX); | |
if (wrap) {while (ret < 0) ret += this.PI2;} | |
return ret; | |
}, | |
}; | |
// export the MathX object | |
module.exports = MathX; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment