1. 程式人生 > 其它 >unity如何讓人物按照指定路線行走(目標點方式)

unity如何讓人物按照指定路線行走(目標點方式)

在unity遊戲開發中如何使物體按照指定的路線運動呢?程式碼如下,這裡是尋找目標點的方式,如果目標點多的話請參照我上一篇部落格的方法;

在unity場景中新增一個空物體path 然後在檢查器中新增元件CinemachineSmoothPath,然後在WayPoints新增座標點  Looped的意思是是否閉合路線,如果你需要閉合路線那就勾選上,我這裡專案需求是不閉合

 然後新建一個指令碼LoopPath

程式碼如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LoopPath1 : MonoBehaviour
{
public GameObject gameObject;
public Button[] buttons;

public GameObject[] gos; //獲取每個目標點,,注意陣列順序不能亂
public float speed = 3; //用於控制移動速度
int i = 0; //用於記錄是第幾個目標點
float des; //用於儲存與目標點的距離

// Update is called once per frame
void Update()
{
//看向目標點
this.transform.LookAt(gos[i].transform);
//計算與目標點間的距離
des = Vector3.Distance(this.transform.position, gos[i].transform.position);
//Debug.Log(Input.text);
////移向目標
transform.position = Vector3.MoveTowards(this.transform.position, gos[i].transform.position, Time.deltaTime * speed);
int x = 1;
//如果移動到當前目標點,就移動向下個目標
if (des < 0.1f && i < gos.Length - 1)
{
i++;
}
}


}