Skip to content

Instantly share code, notes, and snippets.

@Cazra
Created January 18, 2015 03:29
Show Gist options
  • Save Cazra/8d7fdd5f1975c7b28605 to your computer and use it in GitHub Desktop.
Save Cazra/8d7fdd5f1975c7b28605 to your computer and use it in GitHub Desktop.
A small library of vector math functions used by some of my Roll20 scripts
/** Returns an array representing a 2D vector from pt1 to pt2. */
var vec = function(pt1, pt2) {
return [pt2[0]-pt1[0], pt2[1]-pt1[1]];
}
/** Returns the length of an array representing a vector. */
var vecLength = function(vector) {
var length = 0;
for(var i=0; i < vector.length; i++) {
length += vector[i]*vector[i];
}
return Math.sqrt(length);
}
/** Returns an array representing the cross product of two 3D vectors. */
var vecCrossProduct = function(v1, v2) {
var x = v1[1]*v2[2] - v1[2]*v2[1];
var y = v1[2]*v2[0] - v1[0]*v2[2];
var z = v1[0]*v2[1] - v1[1]*v2[0];
return [x, y, z];
}
/** Returns the cross product of two vectors. */
var vecDotProduct = function(v1, v2) {
var result = 0;
for(var i = 0; i < v1.length; i++) {
result += v1[i]*v2[i];
}
return result;
}
/** Computes the distance from a point to an infinitely stretching line. */
var ptLineDist = function(pt, linePt1, linePt2) {
var a = vec(linePt1, linePt2);
var b = vec(linePt1, pt);
var lenA = vecLength(a);
var lenAxB = vecLength(vecCrossProduct(a, b));
if(lenA == 0) {
return NaN;
}
else {
return lenAxB/lenA;
}
}
/** Computes the distance from a point to a line segment. */
var ptSegDist = function(pt, linePt1, linePt2) {
var a = vec(linePt1, linePt2);
var b = vec(linePt1, pt);
a[2] = 0;
b[2] = 0;
// log(a);
// log(b);
var aDotb = vecDotProduct(a,b);
// log("aDotb = " + aDotb);
// Is pt behind linePt1?
if(aDotb < 0) {
// log("pt before");
return vecLength(vec(pt, linePt1));
}
// Is pt after linePt2?
else if(aDotb > vecDotProduct(a,a)) {
// log("pt after");
return vecLength(vec(pt, linePt2));
}
// Pt must be between linePt1 and linePt2.
else {
// log("pt between");
var lenA = vecLength(a);
var AxB = vecCrossProduct(a,b);
var lenAxB = vecLength(AxB);
// log("lenA = " + lenA);
// log("AxB = " + AxB);
// log("lenAxB = " + lenAxB);
return Math.abs(lenAxB/lenA);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment