1、在Unity中使用A*尋路方法步驟(這里暫不對A*算法進行講解)
(1)導入A*尋路插件(該插件需要在較高版本使用【例如2017,5.6無法使用】)—搭建場景—場景中設置兩個層級,地面(Ground)和障礙物(Obstacle)且分別為地面和障礙物設置對應的層—設置兩個標簽,地面(Ground)和障礙物(Obstacle)且分別為地面和障礙物設置對應的標簽
(2)創建一個空物體命名為“A*”,為其添加Astar Path組件(組件庫中搜Pathfinder組件或【Components–>Pathfinding–>Pathfinder】),用於設置尋路參數
(3)在Astar Path組件的Graphs選項中選擇Grid Graph—在面板中對各種參數進行詳細設置—點擊Scan可查看場景中形成的網格
(4)為尋路物體添加Seeker腳本—創建C#腳本,編譯代碼,並掛載到尋路物體上
using System.Collections; using System.Collections.Generic; using UnityEngine; using Pathfinding;//需要引入Pathfinding public class MySkker : MonoBehaviour { public GameObject target; //目標物 private Seeker seeker1; private Path path1; //路徑 private float nextwaypointDistance=1; //距離下一個點的距離 private int currentwaypoint = 0; //當前路點 public float speed = 100; public float rotspeed = 60; //旋轉速度 // Use this for initialization void Start () { seeker1 = this.GetComponent<Seeker>(); seeker1.pathCallback += OnpathCompeleter; seeker1.StartPath(transform.position,target.transform.position); } // Update is called once per frame void Update () { if (path1==null) { print("為空了"); return; } if (currentwaypoint>=path1.vectorPath.Count) { return; } Vector3 dir = (path1.vectorPath[currentwaypoint] - transform.position).normalized; dir *= speed * Time.deltaTime; transform.Translate(dir,Space.World); Quaternion targetrotation = Quaternion.LookRotation(dir); transform.rotation = Quaternion.Slerp(transform.rotation,targetrotation,Time.deltaTime*rotspeed); if (Vector3.Distance(transform.position,path1.vectorPath[currentwaypoint]) < nextwaypointDistance){ currentwaypoint++; return; } } private void OnpathCompeleter(Path p) { if (!p.error) { path1=p; currentwaypoint = 0; } } }