HTML
导入代码模板:
this.x = x || 0;
this.y = y || 0;
return this;
};
Vector2.prototype.add = function(vector){
this.x += vector.x;
this.y += vector.y;
return this;
};
Vector2.prototype.sub = function(vector){
this.x -= vector.x;
this.y -= vector.y;
return this;
};
Vector2.prototype.mult = function(a){
if(typeof a == "object"){
this.x *= a.x;
this.y *= a.y;
} else if (typeof a == "number"){
this.x *= a;
this.y *= a;
}
return this;
};
Vector2.prototype.norm = function(){
var mag = this.mag()
this.x /= mag;
this.y /= mag;
return this;
};
Vector2.prototype.setMag = function(e){
this.normalize();
this.mult(e);
return this;
};
Vector2.prototype.direction = function(e){
return Math.atan2(this.y, this.x);
};
Vector2.prototype.rotate = function(e){
var newDirection = this.direction() + e,
mag = this.mag();
this.x = Math.cos(newDirection) * mag;
this.y = Math.sin(newDirection) * mag;
return this;
};
Vector2.prototype.mag = function(){
return Math.sqrt((this.x*this.x) + (this.y*this.y));
};
Vector2.prototype.angleTo = function(vector){
var angle = Math.atan2(vector.x - this.x, vector.y - this.y);
return angle;
};
Vector2.prototype.distanceTo = function(vector){
return Math.sqrt(Math.pow(vector.x - this.x, 2) + Math.pow(vector.y - this.y, 2));
};
Vector2.prototype.copy = function(){
return new Vector2(this.x, this.y);
};
Vector2.prototype.set = function(){
var args = arguments
if(args.length == 1){
if(typeof args[0] == "object"){
this.x = args[0].x;
this.y = args[0].y;
} else if (typeof args[0] == "number"){
this.x = args[0];
this.y = args[0];
}
} else if (args.length == 2){
this.x = args[0];
this.y = args[1];
}
return this;
};
Vector2.prototype.map = function(vXmin, vXmax, vYmin, vYmax){
if(vXmin < this.x < vXmax && vYmin < this.y < vYmax){
return this;
}
this.x < vXmin ? this.x = vXmin : this;
this.x > vXmax ? this.x = vXmax : this;
this.y < vYmin ? this.y = vYmin : this;
this.y > vYmax ? this.y = vYmax : this;
};
Math.radians = function(deg){
return deg * (Math.PI / 180);
};
Math.degrees = function(rad){
return rad * (180 / Math.PI);
};
random = function(){
if(arguments){
var arg = arguments;
if(arg.length == 1){
return Math.random()*arg[0];
}
if(arg.length == 2){
return Math.random()*( Math.max(arg[0], arg[1])-(Math.min(arg[0], arg[1])) )+Math.min(arg[0], arg[1]);
}
} else {
return Math.random();
}
};