Vector2 Object
A basic Vector2 object with multiple built-in functions.
by Carl Baumann
HTML
Vector2 Objects
JavaScript
function Vector2(x=0,y=0) {
this.x = x;
this.y = y;
this.str = function() {
return "x: " + this.x + " y:" + this.y;
}
this.magnitude = function() {
return Math.sqrt(this.x*this.x + this.y*this.y);
}
this.sqrdMagnitude = function() {
return (this.x*this.x + this.y*this.y);
}
this.normalized = function() {
let temp = new Vector2();
temp.x = this.x / this.magnitude();
temp.y = this.y / this.magnitude();
return temp;
}
this.add = function(v2) {
let temp = new Vector2();
temp.x = this.x + v2.x;
temp.y = this.y + v2.y;
return temp;
}
this.subtract = function(v2) {
let temp = new Vector2();
temp.x = this.x - v2.x;
temp.y = this.y - v2.y;
return temp;
}
this.scale = function(scl) {
let temp = new Vector2();
temp.x = this.x * scl;
temp.y = this.y * scl;
return temp;
}
this.dot = function(v2) {
return this.x*v2.x + this.y*v2.y;
}
}