Created
September 5, 2011 12:39
-
-
Save joshpencheon/1194877 to your computer and use it in GitHub Desktop.
vector
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
var V = { | |
init: function(x, y, z) { | |
return { x: x, y: y, z: z }; | |
}, | |
add: function(v1, v2) { | |
return { | |
x: v1.x + v2.x, | |
y: v1.y + v2.y, | |
z: v1.z + v2.z | |
}; | |
}, | |
joining: function(v1, v2) { | |
return V.add(v2, V.scale(v1, -1)); | |
}, | |
dot: function(v1, v2) { | |
return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; | |
}, | |
product: function(v1, v2) { | |
return { | |
x: v1.y * v2.z - v1.z * v2.y, | |
y: v1.z * v2.x - v1.x * v2.z, | |
z: v1.x * v2.y - v1.y * v2.x | |
}; | |
}, | |
areEqual: function(v1, v2) { | |
return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z); | |
}, | |
scale: function(v, k) { | |
return { | |
x: v.x * k, | |
y: v.y * k, | |
z: v.z * k | |
}; | |
}, | |
isLinearMultiple: function(v1, v2) { | |
if (V.isZero(v1) && V.isZero(v2)) { return true } | |
else if (V.isZero(v1)) { return false } | |
else { | |
if (!v1.x == 0) { return V.areEqual(v1, V.scale(v2, (v1.x / v2.x))) } | |
if (!v1.y == 0) { return V.areEqual(v1, V.scale(v2, (v1.y / v2.y))) } | |
if (!v1.z == 0) { return V.areEqual(v1, V.scale(v2, (v1.z / v2.z))) } | |
} | |
}, | |
isZero: function(v) { | |
return V.areEqual(v, V.init(0, 0, 0)); | |
}, | |
normalize: function(v) { | |
var length = V.magnitude(v); | |
return { | |
x: v.x / length, | |
y: v.y / length, | |
z: v.z / length | |
}; | |
}, | |
magnitude: function(v) { | |
return Math.sqrt(v.x*v.x + v.y*v.y + v.z*v.z); | |
} | |
}; | |
/* | |
The picture: | |
[P] | |
[C] | | |
/ ^ | |
/\ p | |
t e | |
s r | |
e p | |
d | | |
/ | | |
/ | | |
[A]---- s o u r c e > ---------------------[B] | |
Where (A->C = dest), (A->B = source), (B=>P = perp) | |
*/ | |
// Position vectors: | |
var a = V.init(0, 0, 0), | |
b = V.init(1, 2, 0), | |
c = V.init(1, 1, 1); | |
// Direction vectors: | |
var source = V.joining(a, b), | |
dest = V.joining(a, c); | |
// Othogonal component of source vector, with respect to destination vector. | |
var perp = V.normalize(V.product(V.product(source, dest), source)); | |
if (V.magnitude(V.joining(perp, c)) > V.magnitude(V.joining(b, c))) { perp = V.scale(perp, -1) }; | |
console.log("x: " + perp.x + " y: " + perp.y + " z: " + perp.z) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment