とりあえずベクトル計算を行いたかったので、こんなプログラムを作ってみた。3次元ベクトルの足算、引算、内積、外積、正規化を行える...はず
var Vector3 = function(){ this.elements = new Array(0.0, 0.0, 0.0); this.set = function(x, y, z){ this.elements[0] = x; this.elements[1] = y; this.elements[2] = z; return this; } this.seta = function(other){ for(var i = 0; i < 3; i++){ this.elements[i] = other[i]; } return this; } this.setv = function(other){ for(var i = 0; i < 3; i++){ this.elements[i] = other.elements[i]; } return this; } this.add = function(other){ for(var i = 0; i < 3; i++){ this.elements[i] += other.elements[i]; } return this; } this.sub = function(other){ for(var i = 0; i < 3; i++){ this.elements[i] -= other.elements[i]; } return this; } this.length = function(){ var ret = 0.0; for(var i = 0; i < 3; i++){ ret += this.elements[i] * this.elements[i]; } return Math.sqrt(ret); } this.normalize = function(){ var length = this.length(); for(var i = 0; i < 3; i++){ this.elements[i] /= length; } return this; } this.dot = function(other){ var ret = 0.0; for(var i = 0; i < 3; i++){ ret += this.elements[i] * other.elements[i]; } return ret; } this.cross = function(other){ return new Vector3().set( this.elements[1] * other.elements[2] - this.elements[2] * other.elements[1], this.elements[2] * other.elements[0] - this.elements[0] * other.elements[2], this.elements[0] * other.elements[1] - this.elements[1] * other.elements[0] ); } } Vector3.add = function(v1, v2){ return new Vector3().setv(v1).add(v2); } Vector3.sub = function(v1, v2){ return new Vector3().setv(v1).sub(v2); } Vector3.dot = function(v1, v2){ return v1.dot(v2); } Vector3.cross = function(v1, v2){ return v1.cross(v2); }