1.创建几个带有相同Tag的物体,给予不同的坐标;
2.将相同的Tag的物体放到一个父类里面;
3.代码部分
public class MovePath : MonoBehaviour
{
public List<Transform> pointPatch=new List<Transform>();
public static MovePath intstence;
// Use this for initialization
void Start () {
if (intstence == null)
intstence = this;
for (int i = 0; i < transform.childCount; ++i)
{
Transform t = transform.Find("Cube" + i);//寻找子类
if (t != null)
pointPatch.Add(t);
}
}
4,创建一个寻找的物体,物体的代码如下:
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Cubes");
if (go)
{
MovePath mp = go.GetComponent<MovePath>();
if (mp)
movePath = mp;
}
}
void Update () {
if((transform.position - movePath.pointPatch[index].position).magnitude<distance)
{
index++;
if(index>=movePath.pointPatch.Count)
index=0;
}//获取Cubes里的每个子类
Vector3 moveDir=(movePath.pointPatch[index].position-transform.position).normalized;//两个物体之间的单位向量
GetComponent<Rigidbody>().velocity = moveDir * speed;//刚体的速度等于单位向量乘以速度
moveDir = Vector3.Lerp(transform.forward, GetComponent<Rigidbody>().velocity, 0.01f);//物体的方向矫正
transform.forward = moveDir;
transform.position = Vector3.MoveTowards(transform.position, movePath.pointPatch[index].position, 1f);
}
}
magnitude :返回向量的长度(只读)。
normalized :返回向量的长度为1(只读)。
velocity:刚体速度。
Vector3.Lerp:线性插值。
5,方法拓展
利用此方法还可以写某些游戏里面需要追踪的物体(追踪弹),还可以作为物体的行动路径。