zoukankan      html  css  js  c++  java
  • 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()就是获取单位向量,因为向量是有方向的,所以点也就知道移动的方向了。

  • 相关阅读:
    P4995 跳跳!
    P4306 [JSOI2010]连通数
    P1339 [USACO09OCT]热浪Heat Wave
    P2002 消息扩散
    P3388 【模板】割点(割顶)
    P1656 炸铁路
    P2863 [USACO06JAN]牛的舞会The Cow Prom
    P1516 青蛙的约会
    3.从尾到头打印链表
    2.替换空格
  • 原文地址:https://www.cnblogs.com/cnundefined/p/7065149.html
Copyright © 2011-2022 走看看