close
程式碼來源: https://blog.csdn.net/BIGMAD/article/details/71698310
---- 以下是編輯路徑腳本 ----
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EditorPathScript : MonoBehaviour {
public Color rayColor = Color.red;
public List path_objs = new List();
Transform[] theArray;
void OnDrawGizmos(){
Gizmos.color = rayColor;
theArray = GetComponentsInChildren();
path_objs.Clear();
foreach(Transform path_obj in theArray){
if(path_obj != this.transform)
path_objs.Add(path_obj);
}
for(int i = 0;i0){
Vector3 previous = path_objs[i-1].position;
Gizmos.DrawLine(previous,position);
Gizmos.DrawWireSphere(position, 0.3f);
}
}
}
}
---- 以下是物件跟隨行為腳本 ----
using UnityEngine;
using System.Collections;
public class FollowPath : MonoBehaviour {
public bool StartFollow = false;
public EditorPathScript PathToFollow;
public int CurrentWayPointID = 0;
public float Speed;//移动速度
public float reachDistance = 0f;//里路径点的最大范围
public string PathName;//跟随路径的名字
private string LastName;
private bool ChangePath = true;
void Start () {
}
void Update () {
if (!StartFollow)
return;
if (ChangePath)
{
PathToFollow = GameObject.Find(PathName).GetComponent();
ChangePath = false;
}
if (LastName != PathName)
{
ChangePath = true;
}
LastName = PathName;
float distance = Vector3.Distance(PathToFollow.path_objs[CurrentWayPointID].position, transform.position);
//transform.Translate(PathToFollow.path_objs[CurrentWayPointID].position * Time.deltaTime * Speed, Space.Self);
transform.position = Vector3.MoveTowards(transform.position, PathToFollow.path_objs[CurrentWayPointID].position, Time.deltaTime * Speed);
if (distance <= reachDistance)
{
CurrentWayPointID++;
}
if (CurrentWayPointID >= PathToFollow.path_objs.Count)
{
CurrentWayPointID = 0;
}
}
}
文章標籤
全站熱搜
留言列表