Follow Path -》 Unity3d通用脚本

 

 

PathDefinition.cs

 

 1 using UnityEngine;
 2 using System.Collections;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 
 6 public class PathDefinition : MonoBehaviour
 7 {
 8     public Transform[] LinePoint;
 9     List<string> test = new List<string>();
10 
11     public IEnumerator<Transform> GetPathEnumeratror() {
12         if (LinePoint == null || LinePoint.Length < 1)
13             yield break;
14 
15         int direction = 1;
16         int index = 0;
17 
18         while (true) {
19             yield return LinePoint[index];
20 
21             if (LinePoint.Length == 1) continue;
22 
23             if (index <= 0) direction = 1;
24             else if (index >= (LinePoint.Length - 1)) direction = -1;
25 
26             index = index + direction;
27         }
28     }
29 
30     void OnDrawGizmos()
31     {
32         if (LinePoint == null && LinePoint.Length < 2) return;
33 
34         /// filter null
35         var Points = LinePoint.Where(t => t != null).ToList();
36 
37         if (Points.Count < 2) return;
38 
39         for (int i = 1; i < LinePoint.Length; i++)
40         {
41             Vector3 start = LinePoint[i - 1].position;
42             Vector3 end = LinePoint[i].position;
43             Gizmos.DrawLine(start, end);
44         }
45 
46     }
47 }

 

 

FollowPath.cs

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class FollowPath : MonoBehaviour {

    public enum FollowType
    {
        MoveToward,
        Lerp
    }


    public FollowType Type = FollowType.MoveToward;

    public PathDefinition Path;

    public float Speed = 1;

    public float MaxDistanceToGoal = .1f;

    IEnumerator<Transform> _currentPoint;

    public void Start() {
        if (Path == null) {
            return;
        }

        _currentPoint = Path.GetPathEnumeratror();
        
        _currentPoint.MoveNext();

        //set position at start point
        if (_currentPoint.Current == null) return;

        transform.position = _currentPoint.Current.position;
    }

    void Update() {
        if (_currentPoint == null || _currentPoint.Current == null)  return;

        if(Type == FollowType.MoveToward)
            transform.position = Vector3.MoveTowards(transform.position,_currentPoint.Current.position,Speed*Time.deltaTime);
        else if(Type == FollowType.Lerp)
            transform.position = Vector3.Lerp(transform.position, _currentPoint.Current.position, Speed * Time.deltaTime);

        var distanceSquared = (transform.position - _currentPoint.Current.position).sqrMagnitude;
        if (distanceSquared < MaxDistanceToGoal * MaxDistanceToGoal) {
            _currentPoint.MoveNext();
        }
    }
    
}

 

代码 很简单 我就不注释了,比较适用于 路径 编辑 跟踪

posted @ 2014-12-09 00:43  灵魂重新  阅读(206)  评论(0编辑  收藏