using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Linq;
publicclass PathDefinition : MonoBehaviour {
public Transform[] points;//路径点集合public IEnumerator<Transform> GetPathsEnumerator(){//自定义迭代器(用来返回路径点)if (points == null || points.Length < 1)
yieldbreak;
var direction = 1;//移动方向int index = 0;
while (true) {
yieldreturn points [index];
if (points.Length == 1)
continue;
if (index <= 0)
direction = 1;
elseif (index >= points.Length - 1)
direction = -1;
index = index + direction;
}
}
publicvoidOnDrawGizmos(){//重写OnDrawGizmos实现在scene视图中画线if (points==null||points.Length < 2)
return;
var pt = points.Where (t=>t!=null).ToList();//使用的Linq语言集成查询,找出路径点集合中不为空的点if (pt.Count < 2)
return;
for (int i = 1; i < pt.Count; i++) {
Gizmos.DrawLine (pt[i-1].position,pt[i].position);//画线
}
}
}
实现移动
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
publicclass FollowPath : MonoBehaviour {
publicenum FollowType{//定义一个移动类型的枚举
MoveTowards,
Lerp
}
public FollowType type = FollowType.MoveTowards;//默认为直接朝向移动public PathDefinition path;
publicfloat speed = 1;//移动速度publicfloat maxDistanceTOGoal = .1f;//判断物体是否到达某个路径点private IEnumerator<Transform> _currentPoint;//声明一个迭代器void Start(){
if (path == null) {
Debug.Log ("Path cannot be null",gameObject);
return;
}
_currentPoint = path.GetPathsEnumerator ();//获得迭代器实例
_currentPoint.MoveNext ();//MoveNext ()会执行代码到迭代器中yiled 语句处停止(包括yiled 语句)if (_currentPoint.Current == null)//Current代表迭代器当前返回值return;
transform.position = _currentPoint.Current.position;//默认物体初始位置为路径点的第一个位置
}
void Update(){
if (_currentPoint == null || _currentPoint.Current == null)
return;
if (type == FollowType.MoveTowards) {//使用Vector3.MoveTowards移动
transform.position = Vector3.MoveTowards (transform.position, _currentPoint.Current.position, Time.deltaTime * speed);
}
elseif(type==FollowType.Lerp){//使用Vector3.Lerp移动
transform.position = Vector3.Lerp(transform.position,_currentPoint.Current.position,Time.deltaTime*speed);
}
var distanceSquared = (transform.position - _currentPoint.Current.position).sqrMagnitude;
if (distanceSquared < maxDistanceTOGoal * maxDistanceTOGoal)//如果物体与某个路径点的距离的平方小于规定的最大值,则获取下一个路径点
_currentPoint.MoveNext ();
}
}