Skip to content

Instantly share code, notes, and snippets.

@Westixy
Created February 15, 2017 21:38
Show Gist options
  • Save Westixy/d568476d2433e29775cfa1ef3112b9bc to your computer and use it in GitHub Desktop.
Save Westixy/d568476d2433e29775cfa1ef3112b9bc to your computer and use it in GitHub Desktop.
Pos / vecteur
module.exports = class Pos {
static get version(){return '1.0.0';}
constructor(x,y,z) {
this.x=x;
this.y=y;
this.z=z||0;
}
get norme(){
return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);
}
get normeXY(){
return Math.sqrt(this.x*this.x+this.y*this.y);
}
get normeXZ(){
return Math.sqrt(this.x*this.x+this.z*this.z);
}
get angle(){
return Math.atan2(this.y,this.x);
}
get angleZ(){
return Math.atan2(this.z,this.x);
}
get toArray(){
return [this.x,this.y,this.z];
}
get inverse(){
return new this.constructor(this.inverseX,this.inverseY,this.inverseZ)
}
get inverseX(){
return this.x*-1;
}
get inverseY(){
return this.y*-1;
}
get inverseZ(){
return this.z*-1;
}
scalar(pos){
return this.constructor.scalar(this,pos);
}
X(pos){
return this.constructor.X(this,pos);
}
add(pos){
return new this.constructor(this.x+pos.x,this.y+pos.y,this.z+pos.z);
}
until(pos){
return new this.constructor(pos.x-this.x,pos.y-this.y,pos.z-this.z);
}
distance(pos){
return this.until(pos).norme;
}
rotate(rz,ry){
let x=this.x*Math.cos(rz)-this.y*Math.sin(rz);
let y=this.x*Math.sin(rz)+this.y*Math.cos(rz);
let z=0;
if(typeof ry!='undefined'){
let sx=x;
x=sx*Math.cos(ry)-this.z*Math.sin(ry);
z=sx*Math.sin(rz)+this.z*Math.cos(ry);
}
return new this.constructor(x,y,z);
}
translate(x,y,z){
if(typeof x.x!='undefined'){
y=x.y;
z=x.z;
x=x.x;
}else{
y=y||0;
z=z||0;
}
return new this.constructor(this.x+x,this.y+y,this.z+z);
}
equals(x,y,z){
if(typeof x.x!='undefined'){
y=x.y;
z=x.z;
x=x.x;
}else{
y=y||0;
z=z||0;
}
return (x==this.x&&y==this.y&&z==this.z);
}
static create(normeXY,rz,normeXZ,ry){
let x=normeXY*Math.cos(rz);
let y=normeXY*Math.sin(rz);
let z=0;
if(typeof normeXZ!='undefined')if(typeof ry!='undefined'){
z=normeXZ*Math.sin(ry);
}else{console.error('Missing argument "ry" for Pos.create');}
return new this(parseFloat(x.toPrecision(9)),parseFloat(y.toPrecision(9)),parseFloat(z.toPrecision(9)));
}
static X(pos1,pos2){
return new this(
pos1.y*pos2.z-pos1.z*pos2.y,
pos1.z*pos2.x-pos1.x*pos2.z,
pos1.x*pos2.y-pos1.y*pos2.x);
}
static scalar(pos1,pos2){
return pos1.x*pos2.x+pos1.y*pos2.y+pos1.z*pos2.z;
}
static fromArray(arr){
return new this(arr[0],arr[1],arr[2]||0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment