Skip to content

Instantly share code, notes, and snippets.

@lightjiao
Created August 5, 2022 05:24
Show Gist options
  • Save lightjiao/d39a6e304332ba424463c588e29a0de7 to your computer and use it in GitHub Desktop.
Save lightjiao/d39a6e304332ba424463c588e29a0de7 to your computer and use it in GitHub Desktop.
CatmullRomSpline曲线
using System.Collections.Generic;
using UnityEngine;
public static class CatmullRomSpline
{
public static void DrawCatmullRomSpline(LineRenderer lineRenderer, params Vector3[] targets)
{
if (targets == null || targets.Length <= 0) return;
var pos = new List<Vector3>();
var current = 0;
// 绘制 0 ~ n-1
for (; current < targets.Length - 1; current++)
{
// 第一个点相关的四个点为 0,0,1,2
if (current == 0)
{
GetCatmullRomSplinePos(pos, targets[0], targets[0], targets[1], targets[2]);
}
// 倒数第二个点 n-3, n-2, n-1, n-1
else if (current == targets.Length - 2)
{
GetCatmullRomSplinePos(pos, targets[current - 1], targets[current], targets[current + 1], targets[current + 1]);
}
else
{
GetCatmullRomSplinePos(pos, targets[current - 1], targets[current], targets[current + 1], targets[current + 2]);
}
}
lineRenderer.positionCount = pos.Count;
lineRenderer.SetPositions(pos.ToArray());
}
private static void GetCatmullRomSplinePos(List<Vector3> pos, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3)
{
var resulotion = 0.01f;
var loops = Mathf.FloorToInt(1f / resulotion);
for (var i = 0; i <= loops; i++)
{
pos.Add(GetCatmullRomPosition(i * resulotion, p0, p1, p2, p3));
}
}
private static Vector3 GetCatmullRomPosition(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3)
{
var a = 2 * p1;
var b = p2 - p0;
var c = 2 * p0 - 5 * p1 + 4 * p2 - p3;
var d = -p0 + 3 * p1 - 3 * p2 + p3;
return 0.5f * (a + (b * t) + (c * t * t) + (d * t * t * t));
}
}
@lightjiao
Copy link
Author

lightjiao commented Aug 5, 2022

推荐阅读:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment