如何使用Tag来实现物体寻路功能

1.创建几个带有相同Tag的物体,给予不同的坐标;

12


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,方法拓展

利用此方法还可以写某些游戏里面需要追踪的物体(追踪弹),还可以作为物体的行动路径。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值