折线拟合、过顶点的曲线(CatmullRom方法)

由于贝塞尔曲线不过顶点,处理起来比较麻烦,选用CatmullRom比较方便。

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

[RequireComponent(typeof(LineRenderer))]
public class MySpline : MonoBehaviour
{
    public List<Transform> gameOjbet_tran = new List<Transform>();
    private List<Vector3> ptsGizmo = new List<Vector3>();

    private void Start()
    {
        List<Vector3> points = new List<Vector3>();
        //首点添加两次
        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]);


        }
    }
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值