using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class AutoMove : MonoBehaviour { public NavMeshAgent agent; public bool showPath; public bool showAhead; public Vector3 startPos; public Vector3 endPos; public bool isStart; public float curPassedTime = 0; public float timeInterval = 2; // Start is called before the first frame update void Start() { agent = GetComponent(); agent.updateRotation = false; agent.updateUpAxis = false; isStart = false; Move(); } // Update is called once per frame void Update() { //curPassedTime += Time.deltaTime; //if (curPassedTime > timeInterval) //{ // curPassedTime = 0; // Move(); //} if (agent.remainingDistance < 0.1) { Move(); } } void Move() { agent.destination = isStart ? startPos : endPos; isStart = !isStart; } public static void DebugDrawPath(Vector3[] corners) { if (corners.Length < 2) { return; } int i = 0; for (; i < corners.Length - 1; i++) { Debug.DrawLine(corners[i], corners[i + 1], Color.blue); } Debug.DrawLine(corners[0], corners[1], Color.red); } private void OnDrawGizmos() { DrawGizmos(agent, showPath, showAhead); } public static void DrawGizmos(UnityEngine.AI.NavMeshAgent agent, bool showPath, bool showAhead) { if (Application.isPlaying) { if (showPath && agent.hasPath) { var corners = agent.path.corners; if (corners.Length < 2) { return; } int i = 0; for (; i < corners.Length - 1; i++) { Debug.DrawLine(corners[i], corners[i + 1], Color.blue); Gizmos.color = Color.blue; Gizmos.DrawSphere(agent.path.corners[i + 1], 0.03f); Gizmos.color = Color.blue; Gizmos.DrawLine(agent.path.corners[i], agent.path.corners[i + 1]); } Debug.DrawLine(corners[0], corners[1], Color.blue); Gizmos.color = Color.red; Gizmos.DrawSphere(agent.path.corners[1], 0.03f); Gizmos.color = Color.red; Gizmos.DrawLine(agent.path.corners[0], agent.path.corners[1]); } if (showAhead) { Gizmos.color = Color.yellow; Gizmos.DrawRay(agent.transform.position, agent.transform.up * 0.5f); } } } }