您的位置:首页 > 移动开发 > Unity3D

Unity按固定路线自动寻路

2017-08-25 21:48 274 查看


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,t
4000
ransform.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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: