由于贝塞尔曲线不过顶点,处理起来比较麻烦,选用CatmullRom比较方便。
using PathCreation;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(LineRenderer))]
public class MySpline : MonoBehaviour
{
public List gameOjbet_tran = new List();
private List ptsGizmo = new List();
private void Start()
{
List points = new List();
//首点添加两次
points.Add(gameOjbet_tran[0].transform.position);
for (int i = 0; i < gameOjbet_tran.Count; i++)
{
points.Add(gameOjbet_tran[i].transform.position);
}
//尾点添加两次
points.Add(gameOjbet_tran[gameOjbet_tran.Count-1].transform.position);
for (int j = 0; j < 60; j++)
{
Vector3 pt = Interp(points.ToArray(), (float)j / 60.0f);
ptsGizmo.Add(pt);
}
}
//插值
private Vector3 Interp(Vector3[] pts, float t)
{
t = Mathf.Clamp(t, 0.0f, 2.0f);
int numSections = pts.Length - 3;
int currPt = Mathf.Min(Mathf.FloorToInt(t * numSections), numSections - 1);
float u = t * numSections - currPt;
Vector3 a = pts[currPt];
Vector3 b = pts[currPt + 1];
Vector3 c = pts[currPt + 2];
Vector3 d = pts[currPt + 3];
return .5f * (
(-a + 3f * b - 3f * c + d) * (u * u * u)
+ (2f * a - 5f * b + 4f * c - d) * (u * u)
+ (-a + c) * u
+ 2f * b
);
}
void OnDrawGizmos()//画线
{
Gizmos.color = Color.yellow;
Debug.Log("OnDrawGizmos:" + ptsGizmo.Count);
for (int i = 0; i < ptsGizmo.Count - 1; i++)
{
Gizmos.DrawLine(ptsGizmo[i], ptsGizmo[i + 1]);
}
}
}