野怪按路標尋路系統程式碼
阿新 • • 發佈:2022-03-15
野怪按路標尋路系統程式碼
第一次旋轉 沒有動畫版本的
using UnityEngine; public class Tiktik : MonoBehaviour { [SerializeField] private float moveSpeed;//移動速度 [SerializeField] private Transform[] wayPoints;//儲存路標transform資訊 [SerializeField] private int index; //整數變數 用來標陣列下標數 [SerializeField] private float rotationSpeed;//旋轉速度 private bool isTurn;//判斷是否可以旋轉 private void Update() { //沿著起始位置 到終點(是一個座標陣列)位置移動 transform.position = Vector2.MoveTowards(transform.position, wayPoints[index].position, moveSpeed * Time.deltaTime); //MARKER Rotation Animation if (isTurn)//如果轉動為正 TurnRotation(); //如果離目標距離小於0.05的時候 if (Vector2.Distance(transform.position, wayPoints[index].position) <= 0.05f)//CORNER { index++;//轉到下一下目標點 (陣列下標+1) isTurn = true;//轉到狀態加為真 =》執行轉動 if (index > wayPoints.Length - 1)//下標 index >= 陣列.Length { index = 0;//重置 } } } //這次是按尤拉角旋轉的 private void TurnRotation() { //旋轉角度 等於 新的3維向量 X Y軸不變 Z軸等於原來的Z值加上 路標的Z值(度數) transform.eulerAngles = new Vector3(0,0,transform.eulerAngles.z + wayPoints[index].transform.eulerAngles.z); }
ndex 起始下標為1 因為第一個0是不轉的
這幾個路標要排好序 左右的路標Y軸對齊 上下路標 X軸對齊。
index 起始下標為1 因為第一個0是不轉的
這幾個路標要排好序 左右的路標Y軸對齊 上下路標 X軸對齊。
下圖表示每個路標的rotation都要設定 這樣走到了以後 就按這個標的Z軸旋轉
下面為最終程式碼
public class Tiktik : MonoBehaviour { [SerializeField] private float moveSpeed;//移動速度 [SerializeField] private Transform[] wayPoints;//儲存路標transform資訊 [SerializeField] private int index; //整數變數 用來標陣列下標數 [SerializeField] private float rotationSpeed;//旋轉速度 private bool isTurn;//判斷是否可以旋轉 private void Update() { //沿著起始位置 到終點(是一個座標陣列)位置移動 transform.position = Vector2.MoveTowards(transform.position, wayPoints[index].position, moveSpeed * Time.deltaTime); //MARKER Rotation Animation if(isTurn)//如果轉動為正 TurnRotation(); //如果離目標距離小於0.05的時候 if (Vector2.Distance(transform.position, wayPoints[index].position) <= 0.05f)//CORNER { index++;//轉到下一下目標點 (陣列下標+1) isTurn = true;//轉到狀態加為真 =》執行轉動 if (index > wayPoints.Length - 1)//下標 index >= 陣列.Length { index = 0;//重置 } } } private void TurnRotation() { //一個 Quaternion,用於儲存變換在世界空間中的旋轉。 //public static Quaternion RotateTowards (Quaternion from, Quaternion to, float maxDegreesDelta); //form(移動者角度,目標座標的旋轉角度rotation (事先設定好 走過去直接就轉了) ,乘以最角度數) transform.rotation = Quaternion.RotateTowards(transform.rotation, wayPoints[index].rotation, rotationSpeed * Time.deltaTime); } }
附件:原始碼