Unity按固定路线自动寻路

Unity按固定路线自动寻路_第1张图片

using UnityEngine;
using System.Collections;
using System;

public class NavigationHyp1 : MonoBehaviour {
    GameObject[] hypPathPoints;
    int hypNextPathPointsIndex = 1;
    // Use this for initialization
    void Start () {
        hypPathPoints = GameObject.FindGameObjectsWithTag("HypPath");
        //得到的数组是反序的,下面对数组排序,两种方法:
        //Array.Reveres(hypPathPoints);
        Array.Sort(hypPathPoints, (x, y) => { return x.gameObject.name.CompareTo(y.gameObject.name); });
        //先到达第一个点的位置  
        transform.position = hypPathPoints[0].transform.position;
        //方向 
        transform.forward = hypPathPoints[hypNextPathPointsIndex].transform.position - transform.position;
    }
    // Update is called once per frame
    void Update () {
        if (Vector3.Distance(hypPathPoints[hypNextPathPointsIndex].transform.position,transform.position)<0.1f)
        {       //判断的是物体是否到达最后一个点
            if (hypNextPathPointsIndex!=hypPathPoints.Length-1)
            {
                hypNextPathPointsIndex++;
            }
            //物体到达最后一个点后停在 最后一个点的位置
            if (Vector3.Distance(hypPathPoints[hypPathPoints.Length-1].transform.position,transform.position)<0.1f)
            {
                transform.position = hypPathPoints[hypPathPoints.Length - 1].transform.position;
                return;
            }
            //方向的改变
            transform.forward = hypPathPoints[hypNextPathPointsIndex].transform.position - transform.position;
        }
        transform.Translate(Vector3.forward * 5 * Time.deltaTime, Space.Self);
    }
}

//这是一个物体的的寻路就完成了,然后博主是加了一个克隆和销毁的脚本

using UnityEngine;
using System.Collections;

public class InsHyp : MonoBehaviour {
    float timer;
    public GameObject hypTarget;
    // Use this for initialization
    void Start () {

    }   
    // Update is called once per frame
    void Update () {
        timer += Time.deltaTime;
        if (timer>=2)
        {
            timer = 0;
            GameObject.Instantiate(hypTarget);
        }
        Destroy(hypTarget, 10);    
    }
}

你可能感兴趣的:(unity)