Javascript 向量簡單應用

來源:互聯網
上載者:User

本人學習基本上參考了他們三位,在這裡感謝他們的分享 當耐特專家 岑安 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()就是擷取單位向量,因為向量是有方向的,所以點也就知道移動的方向了。

效果示範

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.