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

  • 相关阅读:
    Spring 结合 Hibernate 配置 C3P0
    servlet直接调用spring的serivce方法
    http协议 web开发的应用 笔记
    一个让微软晕倒的中国人,绝对经典
    经典的上课插嘴
    教授说接吻
    在狼身上值得我们学习的十大处世哲学(经典)
    结婚前的暴强对话
    小笑话
    非一般的分手信
  • 原文地址:https://www.cnblogs.com/cnundefined/p/7065149.html
Copyright © 2020-2023  润新知