using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class FollowPathMove : MonoBehaviour
{public Transform[] wayPointArray;[SerializeField] private Transform PathA;//路径点的父物体[SerializeField]private Transform playerObj;//移动的物体private int index;private Vector3 _currentDirection;//当前角色的前进方向void Start(){if(playerObj==null){Debug.LogError("请将移动的角 色放入参数栏");}//print(PathA.childCount);//获取子物体的数量//开辟空间wayPointArray = new Transform[PathA.childCount];for(int i=0;i<wayPointArray.Length;i++){wayPointArray[i]=PathA.GetChild(i);//将路径点加入数组中//print($"wayPointArrayz{i} ={ wayPointArray[i].position }");//输出世界坐标}}//在Updata里面最好不要放太多东西void Update(){//Distance需要开方/* if (Vector3.Distance(wayPointArray[index].position,playerObj.position)<0.3f){//检查是否到达最后一个目标点if (index < wayPointArray.Length - 1){ index++; }else{index = 0;}*//* if (index++ == wayPointArray.Length - 1){index = 0;}*/// }//返回距离的平方值// Vector3 _currentDirection = wayPointArray[index].position - playerObj.position;//开启协程,每隔1秒钟算10次0.11.5StartCoroutine(RotationDirectionByTime(1.5f));//角色一直前进playerObj.Translate(Vector3.forward * 8f * Time.deltaTime);}IEnumerator RotationDirectionByTime(float time){while (true){//写算法来改变角色前进的方向//计算角色与目标点之间的向量Vector3 _currentDirection = wayPointArray[index].position - playerObj.position;if (_currentDirection.sqrMagnitude <= 0.2f){index += 1;if (index == wayPointArray.Length ){index = 0;}}Debug.Log("输出数组坐标:" + index);//计算旋转角度(没有旋转的过程)// playerObj.LookAt(direction);//差值运算能够看到他的过程,球形差值//出现抖动是因为这里每一帧出来的值都不一样,所以需要用协程控制一下playerObj.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(_currentDirection), 0.9f);//计算旋转角度(没有旋转的过程)//print(_currentDirection.sqrMagnitude);yield return new WaitForSeconds(time);}}
}