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吧

猜你喜欢

转载自blog.csdn.net/cheng219101/article/details/106812178