您当前的位置: 首页 > 

程序员正茂

暂无认证

  • 2浏览

    0关注

    283博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

程序员正茂 发布时间:2020-01-03 19:01:10 ,浏览量:2

由于贝塞尔曲线不过顶点,处理起来比较麻烦,选用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]);


        }
    }
}

 

关注
打赏
1660743125
查看更多评论
立即登录/注册

微信扫码登录

0.0398s