Unity基础,Line Renderer 和射线的应用

来源:互联网 发布:如何在php中定义常量 编辑:程序博客网 时间:2024/05/24 05:38

Line Renderer (线渲染器):

通过鼠标或者手指在屏幕中画线:

     1.声明,判断点击。

[SerializeField]private LineRenderer lineRenderer;private bool firstMouseDown=false;//第一次点击private bool mouseDown=false; //一直点击

private void Update()    {        if (Input.GetMouseButtonDown(0)) {            firstMouseDown = true;            mouseDown = true;        }        if (Input.GetMouseButtonUp(0)) {            mouseDown = false;        }        OnDrawLine(); //调用画线方法        firstMouseDown = false;    }


    2. 画线

    private Vector3[] positions = new Vector3[10];//所有坐标(10个点)    private int posCount = 0;//当前第几个坐标    private Vector3 head;//头坐标    private Vector3 last;//上一次头坐标

     画线:OnDrawLine();

   private void OnDrawLine() {        if (firstMouseDown){            posCount = 0;            head = Camera.main.ScreenToWorldPoint(Input.mousePosition);            last = head;        }        if (mouseDown)        {            head = Camera.main.ScreenToWorldPoint(Input.mousePosition);            if (Vector3.Distance(head, last) > 0.01f)            {                SavePosition(head);                posCount++;            }            OnRayCast(head);            last = head;        }        else {            this.positions = new Vector3[10];        }        ChangePositions(positions);    }

      保存位置坐标:SavePosition( Vector3  pos );

    private void SavePosition(Vector3 pos) {        pos.z = 0;        if (posCount <= 9)        {            for (int i = posCount; i < 10; i++)            {                positions[i] = pos;            }        }        else {            for (int i = 0; i < 9; i++) {                positions[i] = positions[i + 1];            }            positions[9] = pos;        }    }

       设置线的位置方法:ChangePositions( Vector3[ ]  position )

    private void ChangePositions(Vector3[] positions) {        lineRenderer.SetPositions(positions);    }

  发出射线 :OnRayCast(Vector3 worldPos)

    private void OnRayCast(Vector3 worldPos) {        Vector3 screenPos = Camera.main.WorldToScreenPoint(worldPos);        Ray ray = Camera.main.ScreenPointToRay(screenPos);        RaycastHit[] hits = Physics.RaycastAll(ray);        for (int i = 0; i < hits.Length; i++) {            //Destroy(hits[i].collider.gameObject);            hits[i].collider.gameObject.SendMessage("OnCut",SendMessageOptions.DontRequireReceiver);        }    }







         



原创粉丝点击