Javascript 向量

向量

既有大小又有方向的量叫做向量(亦称矢量),与标量相对,用JS实现代码如下,直接搬miloyip的了

Vector2 = function(x, y) { this.x = x; this.y = y; };
 
Vector2.prototype = {
    copy: function() { return new Vector2(this.x, this.y); },
    length: function() { return Math.sqrt(this.x * this.x + this.y * this.y); },
    sqrLength: function() { return this.x * this.x + this.y * this.y; },
    normalize: function() { var inv = 1 / this.length(); return new Vector2(this.x * inv, this.y * inv); },
    negate: function() { return new Vector2(-this.x, -this.y); },
    add: function(v) { return new Vector2(this.x + v.x, this.y + v.y); },
    subtract: function(v) { return new Vector2(this.x - v.x, this.y - v.y); },
    multiply: function(f) { return new Vector2(this.x * f, this.y * f); },
    divide: function(f) { var invf = 1 / f; return new Vector2(this.x * invf, this.y * invf); },
    dot: function(v) { return this.x * v.x + this.y * v.y; }
};

实现效果

  主要实现小方朝某个固定的方向移动,到达目的地后再分散开,重复上面两个步骤。

  为了实现物体朝某个点移动,这里需要进行一个向量的计算

targetPos.subtract(obj.pos).normalize();

如一个点(100,100)移动到目标点(200,200),subtract()返回的就是一个向量,normalize()就是获取单位向量,因为向量是有方向的,所以点也就知道移动的方向了。