本人學習基本上參考了他們三位,在這里感謝他們的分享 當耐特專家 岑安 miloyip
向量
既有大小又有方向的量叫做向量(亦稱矢量),與標量相對,用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()就是獲取單位向量,因為向量是有方向的,所以點也就知道移動的方向了。
效果演示