using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; using XFramework; public class NavMeshManager : MonoBehaviour { public Transform targetPoints; public LineRenderer lineRenderer; NavMeshAgent meshAgent; bool showLine= false; // Start is called before the first frame update void Start() { meshAgent = this.transform.GetOrAddComponent(); if (showLine) { lineRenderer = new GameObject("LineRenderer").transform.GetOrAddComponent(); } } /// /// 设置待寻路的起点 /// /// public void SetStartPos(Vector3 startPos) { if(meshAgent==null) meshAgent = this.transform.GetOrAddComponent(); meshAgent.enabled = false; this.transform.position = startPos; meshAgent.enabled = true; //if (!meshAgent.isOnNavMesh) // meshAgent.Warp(this.transform.position); } /// /// 设置待寻路的终点 并返回该点位置是否可达 返回数组为空时代表不可达 /// /// 终点位置 public Vector3[] SetTargetPointPostion(Vector3 postion) { NavMeshPath meshPath = new NavMeshPath(); meshAgent.CalculatePath(postion, meshPath); if (meshPath.status == NavMeshPathStatus.PathComplete) { meshAgent.enabled = false; this.transform.position = postion; meshAgent.enabled = true; if (lineRenderer) { lineRenderer.positionCount = meshPath.corners.Length; lineRenderer.SetPositions(meshPath.corners); } return meshPath.corners; } else { return null; } } // Update is called once per frame void Update() { //if (Input.GetKeyDown(KeyCode.Space)) //{ // //meshAgent.destination = targetPoints.position; // // Debug.Log("hasPath:" + meshAgent.hasPath); // NavMeshPath meshPath = new NavMeshPath(); // meshAgent.CalculatePath(targetPoints.position, meshPath); // if (meshPath.status == NavMeshPathStatus.PathComplete) // { // Debug.Log("该路点可达"); // lineRenderer.LineCount = meshPath.corners.Length; // lineRenderer.lineRenderer.SetPositions(meshPath.corners); // } // //for (int i = 0; i < meshAgent.path.corners.Length; i++) // //{ // // lineRenderer.AddPostion(meshAgent.path.corners[i]); // //} //} } }