这个代码是从官网的一个Demo中扒出来的,Demo中代码较多,好多用不到,不利于查看核心代码
核心代码
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class WaypointCircuit : MonoBehaviour {
public WaypointList waypointList = new WaypointList();
[SerializeField] bool smoothRoute = true;
int numPoints;
Vector3[] points;
float[] distances;
public float editorVisualisationSubsteps = 100;
public float Length { get; private set; }
public Transform[] Waypoints { get { return waypointList.items; } }
//this being here will save GC allocs
int p0n;
int p1n;
int p2n;
int p3n;
private float i;
Vector3 P0;
Vector3 P1;
Vector3 P2;
Vector3 P3;
// Use this for initialization
void Awake () {
if (Waypoints.Length > 1)
{
CachePositionsAndDistances();
}
numPoints = Waypoints.Length;
}
public RoutePoint GetRoutePoint(float dist)
{
// position and direction
Vector3 p1 = GetRoutePosition(dist);
Vector3 p2 = GetRoutePosition(dist + 0.1f);
Vector3 delta = p2-p1;
return new RoutePoint( p1, delta.normalized );
}
public Vector3 GetRoutePosition(float dist)
{
int point = 0;
if (Length == 0)
{
Length = distances[distances.Length-1];
}
dist = Mathf.Repeat(dist,Length);
while (distances[point] < dist) { ++point; }
// get nearest two points, ensuring points wrap-around start & end of circuit
p1n = ((point-1) + numPoints) % numPoints;
p2n = point;
// found point numbers, now find interpolation value between the two middle points
i = Mathf.InverseLerp(distances[p1n],distances[p2n],dist);
if (smoothRoute)
{
// smooth catmull-rom calculation between the two relevant points
// get indices for the surrounding 2 points, because
// four points are required by the catmull-rom function
p0n = ((point-2) + numPoints) % numPoints;
p3n = (point+1) % numPoints;
// 2nd point may have been the 'last' po