CocosCreator中,在3d世界里画线

示意

画线.gif

步骤

  1. 关注触屏移动事件:Input.EventType.TOUCH_MOVE,获取参数触屏点(event.touch.getLocation())
 input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);

 private onTouchMove(event: EventTouch): void {
        if (this._touchId == event.touch.getID()) {
            this.eventTarget.emit(SingleTouchCtr.SingleTouchMoveEvent, event.touch.getLocation());
        }
    }

  1. 将第1步获得到的点转为世界坐标中的点
    private onTouchMove(pos: Vec2): void
    { 
        this._cam.screenPointToRay(pos.x, pos.y, this._ray);
        if (PhysicsSystem.instance.raycastClosest(this._ray))
        { 
            const r = PhysicsSystem.instance.raycastClosestResult;
            const p = new Vec3(r.hitPoint.x, this._beginNode.worldPosition.y, r.hitPoint.z);
            this._points.push(p);
            this.eventTarget.emit(DrawLineSys.CreatePointEvent, this._points);
        }
    }
  1. 使用Line将点显示出来
    因为Line的Positions超过100个会报错,所以根据实际要绘制的点的数量,先确保有足够的Line,再将点对应到各Line上


    报错
    private drawLine(points: Vec3[]): void
    { 
        const lineCnt = Math.ceil(points.length / 100);
        const newLineCnt = Math.max(0, lineCnt - this._lines.length);
        for (let i = 0; i < newLineCnt; i++)
        {
            const newLine = this._lineTemplate.node.addComponent(Line);
            newLine.width = this._lineTemplate.width;
            newLine.color = this._lineTemplate.color;
            this._lines.push(newLine);
        }

        const tempPoints = new Array<Vec3>();
        for (const p of points)
        { 
            tempPoints.push(p);
        }
        for (let i = 0; i < this._lines.length; i++)
        { 
            const curPoints = tempPoints.splice(0, Math.min(99, tempPoints.length));
            if (tempPoints[0]) {
                curPoints.push(tempPoints[0]);
            }
            this._lines[i].positions = curPoints as never[];
        }
    }
  1. 清除Line
    private clearLines()
    { 
        for (const l of this._lines) {
            l.destroy();
        }
        this._lines.splice(0, this._lines.length);
    }

推荐阅读更多精彩内容