Laya Ts 判断一个点是否在闭合的图形内

先上代码图片 ,后附代码

 // 创建闭合的图形 -(这个坐标大致等于五边形)

        let tempPoint1 = new Laya.Point(200,1500);

        let tempPoint2 = new Laya.Point(830,2800);

        let tempPoint3 = new Laya.Point(2000,2800);

        let tempPoint4 = new Laya.Point(2800,1500);

        let tempPoint5 = new Laya.Point(1500,400);

      

        this.mapPoint.push( tempPoint1 );

        this.mapPoint.push( tempPoint2 );

        this.mapPoint.push( tempPoint3 );

        this.mapPoint.push( tempPoint4 );

        this.mapPoint.push( tempPoint5 );

        this.mapPoint.push( tempPoint1 );

        var sp = new Laya.Sprite();

        this.AddChild(sp);

        // 用红线画出来

        sp.graphics.drawLine(tempPoint1.x, tempPoint1.y,tempPoint2.x,tempPoint2.y,"#ff0000",5);

        sp.graphics.drawLine(tempPoint2.x, tempPoint2.y,tempPoint3.x,tempPoint3.y,"#ff0000",5);

        sp.graphics.drawLine(tempPoint3.x, tempPoint3.y,tempPoint4.x,tempPoint4.y,"#ff0000",5);

        sp.graphics.drawLine(tempPoint4.x, tempPoint4.y,tempPoint5.x,tempPoint5.y,"#ff0000",5);

        sp.graphics.drawLine(tempPoint5.x, tempPoint5.y,tempPoint1.x,tempPoint1.y,"#ff0000",5);

算法判断:

 public InMap(checkPoint :Laya.Point):boolean{

        var counter = 0;

        var i;

        var xinters;

        var p1, p2;

        let polygonPoints = this.mapPoint; // 闭合图形的坐标点

        var pointCount = polygonPoints.length;

        p1 = polygonPoints[0];

        for (i = 0; i < pointCount; i++) {

            p2 = polygonPoints[i];

            if (checkPoint.x > Math.min(p1.x, p2.x) && checkPoint.x <= Math.max(p1.x, p2.x)) {

                if (checkPoint.y <= Math.max(p1.y, p2.y)) {

                    if (p1.x != p2.x) {

                        xinters = (checkPoint.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;

                        if (p1.y == p2.y || checkPoint.y < xinters) {

                            counter++;

                        }

                    }

                }

            }

            p1 = p2;

        }

        if (counter % 2 == 0) {

            return false;

        } else {

            return true;

        }

    }

猜你喜欢

转载自blog.csdn.net/LM514104/article/details/109671950
ts