自動尋路

Unity 內建的 NavMesh 自動尋路系統簡單建置流程:

  1. 定義靜態場景物件 Make Obstacles Static
  2. 定義角色牆面間距 Radius
  3. 定義最低可走區域 Height
  4. 定義可走斜坡角度 Max Slope
  5. 定義可跨越之距離 Step Height
  6. 燒製場景可走區塊 Bake Walkable Area
  7. 新增自動尋路元件 Add NavMeshAgent Component
  8. 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);
          }
      }
    }
    
  9. 手動尋路腳本設計

    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 ();
    }
    
  10. 新增移動式障礙物 Add NavMeshObstacle Component

results matching ""

    No results matching ""