unity3d NavMeshAgent 导航显示路径

版权声明:转载请注明,谢谢 https://blog.csdn.net/qq_38655924/article/details/82986268

using UnityEngine;

using UnityEngine.AI;

 

// Use physics raycast hit from mouse click to set agent destination

[RequireComponent(typeof(NavMeshAgent))]

public class ClickToMove : MonoBehaviour

{

    NavMeshAgent m_Agent;

    RaycastHit m_HitInfo = new RaycastHit();

    public LineRenderer _lineRenderer;

    void Start()

    {

        m_Agent = GetComponent<NavMeshAgent>();

    }

 

    void Update()

    {

 

        if (Mathf.Abs(m_Agent.remainingDistance) < 1.5f)

        {

            _lineRenderer.positionCount = 0;

            _lineRenderer.gameObject.SetActive(false);

        }

        if (_lineRenderer.gameObject.activeInHierarchy)

        {

            Vector3[] _path = m_Agent.path.corners;//储存路径

            var path = _path;

            _lineRenderer.SetVertexCount(_path.Length);//设置线段数

 

            for (int i = 0; i < _path.Length; i++)

            {

                Debug.Log(i + "= " + _path[i]);

                _lineRenderer.SetPosition(i, _path[i]);//设置线段顶点坐标

            }

        }

 

        if (Input.GetMouseButtonDown(0) && !Input.GetKey(KeyCode.LeftShift))

        {

            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray.origin, ray.direction, out m_HitInfo))

            {

                m_Agent.destination = m_HitInfo.point;

                //m_Agent.Stop();

                _lineRenderer.gameObject.SetActive(true);

            }

        }

    }

}

猜你喜欢

转载自blog.csdn.net/qq_38655924/article/details/82986268