unity中如何讓一個對象沿著路徑點循環(huán)移動
已經(jīng)存在一個用于保存所有路徑點的列表public List<Vector3> List_PathPoint = new List<Vector3>();,要讓對象沿著列表的點按照MoveSpeed的速度循環(huán)移動, 可以使用一個指針來指示當(dāng)前應(yīng)該移動到的路徑點的索引,然后在Update函數(shù)中通過Vector3.MoveTowards方法將對象移動到下一個路徑點。當(dāng)對象到達列表中的最后一個路徑點時,將指針重置為0,以便對象可以從頭開始循環(huán)移動。
public List<Vector3> List_PathPoint = new List<Vector3>();
public float MoveSpeed = 5f;
private int currentPathIndex = 0;
void Update()
{
// 獲取當(dāng)前指向的路徑點
Vector3 currentTarget = List_PathPoint[currentPathIndex];
// 計算移動方向和距離
Vector3 moveDirection = currentTarget - transform.position;
float distanceToTarget = moveDirection.magnitude;
// 如果距離小于可以接受的誤差,則移動到下一個路徑點
if (distanceToTarget < 0.1f)
{
currentPathIndex++;
if (currentPathIndex >= List_PathPoint.Count)
{
currentPathIndex = 0;
}
}
else
{
// 向下一個路徑點移動
Vector3 moveVector = moveDirection.normalized * MoveSpeed * Time.deltaTime;
transform.position += moveVector;
}
}
在此示例中,每幀都會計算對象當(dāng)前應(yīng)該移動到的路徑點,并將其向該點移動。如果對象到達路徑點,則將指針移動到下一個路徑點。當(dāng)對象到達列表中的最后一個路徑點時,指針將重置為0,以便對象可以從頭開始循環(huán)移動。