2d向量类 —— js版

function Vector2D(x,y){

this._x = x;

this._y = y;

}

 

Vector2D.angleBetween = function(v1,v2){

if(!v1.isNormalized()){

v1 = v1.clone().normalize();

}

if(!v2.isNormalized()){

v2 = v2.clone().normalize();

}

return Math.acos(v1.dotProd(v2));

};

 

Vector2D.prototype = {

setX : function(x){

this._x = x;

},

getX : function(){

return this._x;

},

setY : function(y){

this._y = y;

},

getY : function(){

return this._y;

},

clone : function(){

return new Vector2D(this._x,this._y);

},

zero : function(){

this._x = 0;

this._y = 0;

return this;

},

isZero : function(){

return this._x == 0 && this._y == 0;

},

setLength : function(length){

var angle = this.getAngle();

this._x = Math.cos(angle) * length;

this._y = Math.sin(angle) * length;

},

getLength : function(){

return Math.sqrt(this.getLengthSQ());

},

getLengthSQ : function(){

return this._x * this._x + this._y * this._y;

},

setAngle : function(angle){

var length = this.getLength();

this._x = Math.cos(angle) * length;

this._y = Math.sin(angle) * length;

},

getAngle : function(){

return Math.atan2(this._y,this._x);

},

normalize : function(){

var length = this.getLength();

if(length == 0){

this._x = 1;

return this;

}

this._x /= length;

this._y /= length;

return this;

},

isNormalized : function(){

return this.getLength() == 1.0;

},

reverse : function(){

this._x = -this._x;

this._y = -this._y;

return this;

},

dotProd : function(v2){

return this._x * v2.getX() + this._y * v2.getY();

},

crossProd : function(v2){

return this._x * v2.getY() - this._y * v2.getX();

},

getPerp : function(){

return new Vector2D(-this._y,this._x);

},

sign : function(v2){

return this.getPerp().dotProd(v2) < 0 ? -1 : 1;

},

dist : function(v2){

return Math.sqrt(this.distSQ(v2));

},

distSQ : function(v2){

var dx = v2.getX() - this._x;

   dy = v2.getY() - this._y;

return dx * dx + dy * dy;

},

add : function(v2){

return new Vector2D(this._x + v2.getX(),this._y + this.getY());

},

subtract : function(v2){

return new Vector2D(this._x - v2.getX(),this._y - v2.getY());

},

multiply : function(n){

return new Vector2D(this._x * n,this._y * n);

},

divide : function(n){

return new Vector2D(this._x / n,this._y / n);

},

equals : function(v2){

return this._x == v2.getX() && this._y == v2.getY();

}

};


转载于:https://www.cnblogs.com/cly84920/archive/2012/04/05/4426533.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值