LayaAir2D向量的使用

刚看完免费视频教程,准备自己写个2D游戏练练手,涉及到向量使用,遇到了问题。
开始直接使用Laya.Vector2,居然一点没报错,只是用起来很不舒服,向量加减感觉都不知道该如何写。运行了几次后,干脆直接就报错了

“Laya.Vector2 is not a constructor”

问了下度娘,有解决方案。

簡單來講,在"index.html"這個檔案裡頭添加<script type="text/javascript" src="libs/laya.d3.js"></script>,即可使用Laya.Vector2。

但是,我做个2D项目为何非得引用3D的库呢?不细究了,自己写个向量类算了

export default class Vect2D
{
    public x : number = 0;
    public y : number = 0;

    constructor(x : number, y : number)
    {
        this.x = x;
        this.y = y;
    }

    public normalized() : Vect2D
    {
        var len : number = Math.sqrt( Math.abs(this.x * this.x) + Math.abs(this.y * this.y))
        var newV : Vect2D = new Vect2D(this.x / len, this.y / len);
        return newV;
    }

    public sum(v : Vect2D) : Vect2D
    {
        var newV : Vect2D = new Vect2D(v.x + this.x, v.y + this.y);
        return newV;
    }

    public diff(v : Vect2D) : Vect2D
    {
        var newV : Vect2D = new Vect2D(this.x - v.x, this.y - v.y);
        return newV;
    }

    public scale(scale : number) : Vect2D
    {
        var newV : Vect2D = new Vect2D(this.x * scale, this.y * scale);
        return newV;
    }
}

这里做个需求,已知一个点A,当鼠标按下时,画一条线连接A和鼠标的位置,并且延长到屏幕边上。代码就很简单了

        var v1 : Vect2D = new Vect2D(x1, y1);
        var v2 : Vect2D = new Vect2D(x2, y2);
        var v : Vect2D = v2.diff(v1).normalized().scale(3000).sum(v1);
        this.sp.graphics.clear();
        //画直线
        this.sp.graphics.drawLine(x1, y1, v.x, v.y , "#ff0000", 1);

以后再琢磨Laya.Vector2吧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值