自動尋路
Unity 內建的 NavMesh 自動尋路系統簡單建置流程:
- 定義靜態場景物件 Make Obstacles Static
- 定義角色牆面間距 Radius
- 定義最低可走區域 Height
- 定義可走斜坡角度 Max Slope
- 定義可跨越之距離 Step Height
- 燒製場景可走區塊 Bake Walkable Area
- 新增自動尋路元件 Add NavMeshAgent Component
RTS角色腳本設計
void Update() { if (Input.GetMouseButtonDown(0)) { Ray screenRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(screenRay, out hit)) { agent.SetDestination(hit.point); } } }
手動尋路腳本設計
void Start () { agent = gameObject.GetComponent<NavMeshAgent>(); NavMeshPath path = new NavMeshPath(); } void FindPath () { if (agent.CalculatePath(destination.position, path)) { if(path.status == NavMeshPathStatus.PathComplete) { print("The agent can reach the destionation"); agent.SetPath (path); } else if(path.status == NavMeshPathStatus.PathPartial) { print("The agent can only get close to the destination"); } else if(path.status == NavMeshPathStatus.PathInvalid) { print("The agent cannot reach the destination"); agent.ResetPath (); } } } void StopMoving () { if (shouldStopImmediately) agent.Stop (true); else // decelerate agent.Stop (); } void ResumeMoving () { agent.Resume (); }
- 新增移動式障礙物 Add NavMeshObstacle Component