Unity19--物体自动沿固定路线走,自动寻路

一、沿固定路线走(创建Nav2文本)

  //1.固定路线走,都给小球设置标签Path01

  //2.把方块Player拖成预制体,写文本CreateEnemeies给了空文件夹,参数count不用填,,可以改程序中的count<   ,Nav2给了预制 

   体,可把小球的Mesh的√去掉,就不显示了

  //3.可写创造一波怪物按固定路线,暂时只能创造一波怪物,等用协程写

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

开始:Nav2文本

1..    publicGameObject[] pathPoints;

     //  public GameObject player;  //去掉player,就不特指某个对象了,如果只是让一个固定对象沿着固定路线走,  就不用克隆的

        那个脚本了,而且也要加上Player,文本给了Player.

   

       //记录下一个路点

       intnextPathPointIndex = 1;

1.void Start () {

        pathPoints = GameObject.FindGameObjectsWithTag("Path01");

      //  Array.Reverse(pathPoints);翻转排序,最简单的方法,下面的排序高大上些。

        Array.Sort(pathPoints, (x, y) => { returnx.gameObject.name.CompareTo(y.gameObject.name); });    //排序,得到所有路点

        transform.position = pathPoints[0].transform.position;

        transform.forward =pathPoints[nextPathPointIndex].transform.position - transform.position;   

         }

2.void Update () {

         if(Vector3.Distance(pathPoints[nextPathPointIndex].transform.position,

            transform.position)<0.1f)

            {

            if(nextPathPointIndex !=pathPoints.Length-1)

            {

                nextPathPointIndex++;

            }

 

            if(Vector3.Distance(pathPoints[pathPoints.Length- 1].transform.position, transform.position)<0.1f)

            {

                transform.position =pathPoints[pathPoints.Length - 1].transform.position;

                return;

            }

            transform.forward =pathPoints[nextPathPointIndex].transform.position - transform.position;

         }

        transform.Translate(Vector3.forward * 5 * Time.deltaTime, Space.Self);//以自己的轴走动

    }

2. CreateEnemeies文本

//克隆产生敌人,生成一波敌人的数量

----------------------------------------------------------------------------------------------------------------------------------------

    float timer = 0;

    float timer2 = 0;

    //产生敌人的速率

    publicfloat rate;

    //敌人的预制体

    publicGameObject enemeyPrefab;

    //每一波的时间

    publicfloat timesofEachWave = 30;

    //每一波的已经产生的数量

    publicint count;

1.void Update () {

        timer2 += Time.deltaTime;

        if (timer2 < timesofEachWave && count != 10)

        {

            timer += Time.deltaTime;

            if (timer > rate)

            {

                Instantiate(enemeyPrefab, Vector3.zero, Quaternion.identity);

                count++;

                timer -= rate;

            }    

        }          

}

Unity19--物体自动沿固定路线走,自动寻路_第1张图片




你可能感兴趣的:(Unity3D)