Created
August 11, 2021 14:41
-
-
Save rzorzal/1f3208e8e9aaa465938767409c2c7760 to your computer and use it in GitHub Desktop.
A implementation ofVector3d in Javascript
This file contains 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
class Vector3d { | |
static toDegrees(radians){ | |
return (radians * 180) / Math.PI; | |
} | |
static toRadian(degrees){ | |
return (degress * Math.PI) / 180; | |
} | |
static create(x,y,z){ | |
return new Vector3d(x,y,z); | |
} | |
constructor(x,y,z){ | |
this.x = x; | |
this.y = y; | |
this.z = z; | |
} | |
add(vector){ | |
const x = this.x + vector.x; | |
const y = this.y + vector.y; | |
const z = this.z + vector.z; | |
return Vector3d.create(x,y,z); | |
} | |
subtract(vector){ | |
const x = this.x - vector.x; | |
const y = this.y - vector.y; | |
const z = this.z - vector.z; | |
return Vector3d.create(x,y,z); | |
} | |
normalize(){ | |
const m = this.length(); | |
const x = this.x/m; | |
const y = this.y/m | |
const z = this.z/m | |
return Vector3d.create(x,y,z); | |
} | |
multScalar(a){ | |
const x = this.x*a; | |
const y = this.y*a | |
const z = this.z*a | |
return Vector3d.create(x,y,z); | |
} | |
length(){ | |
return Math.hypot(this.x, this.y, this.z) | |
} | |
dotProduct(vector){ | |
return this.x*vector.x + this.y*vector.y + this.z*vector.z; | |
} | |
haveSameDirectionWith(vector, EPSILON=0.00000001){ | |
const dot = this.normalize().dotProduct(vector.normalize()); | |
return Math.abs(dot - 1) < EPSILON; | |
} | |
haveOppositeDirectionWith(vector, EPSILON=0.00000001){ | |
const dot = this.normalize().dotProduct(vector.normalize()); | |
return Math.abs(dot + 1) < EPSILON; | |
} | |
isPerpendicularTo(vector, EPSILON=0.00000001){ | |
const dot = this.normalize().dotProduct(vector.normalize()); | |
return Math.abs(dot) < EPSILON; | |
} | |
angleBetween(vector){ | |
const d = this.dotProduct(vector); | |
const l1 = this.length(); | |
const l2 = vector.length(); | |
const c = Math.acos(d / (l1*l2)); | |
return Vector3d.toDegrees(c); | |
} | |
crossProduct(vector){ | |
const x = this.y * vector.z - this.z * vector.y; | |
const y = this.z * vector.x - this.x * vector.z; | |
const z = this.x * vector.y - this.y * vector.x; | |
return Vector3d.create(x,y,z); | |
} | |
negate(vector){ | |
return this.multScalar(-1) | |
} | |
scaleBy(n){ | |
return Vector3d.create(); | |
} | |
projectOn(vector){ | |
const n = vector.normalize(); | |
return n.multScalar(this.dotProduct(n)); | |
} | |
equalsTo(vector){ | |
if(vector.x != this.x) return false; | |
if(vector.y != this.y) return false; | |
if(vector.z != this.z) return false; | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment