unity之贝塞尔曲线

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


 开发思路:
 例如有三个点(A,B,C),我们需要10个轨迹点:第一次计算我们得到了20个点(分别是AB和BC之间各10个点)
 我们再通过二十个点得到10条线,计算出每条线上我们需要的那个轨迹点,就得到了10个轨迹点

public class TextBizer : MonoBehaviour {

    public Transform nodel;   /// 轨迹点的父节点
    public List<Vector3> nodeList = new List<Vector3>();  ///轨迹点的世界坐标
    public List<Vector3> posList = new List<Vector3>();   /// 得到的轨迹点
    public int icount = 10;                               /// 需要轨迹点的数量(数字越大,轨迹线越圆滑)
    private void Start()
    {
        for(int i=0;i<nodel.childCount;i++)
        {
            nodeList.Add(nodel.GetChild(i).position);
        }
        posList =  ComputationalTrajectory(nodeList);
    }
    private void Update()
    {
        if (posList.Count > 0)
        {
            for (int i = 1; i < posList.Count; )
            {
                Debug.DrawLine(posList[i - 1], posList[i], Color.red);
                i = i + 1;
            }
        }
    }
    /// 采用递归的思想来完成贝塞尔曲线,可以实现n阶的贝塞尔曲线
    List<Vector3> ComputationalTrajectory(List<Vector3> tempPos)
    {
        List<Vector3> tempNewList = new List<Vector3>();
        foreach(var temp in tempPos)
        {
            tempNewList.Add(temp);
        }
        
        if (tempPos.Count == icount)   /// 当得到的轨迹点的数量是我们需要的数量就返回
        {
            posList.Add(nodel.GetChild(nodel.childCount-1).position);
            return tempPos;
        }
        else if (tempPos.Count > icount)   /// 当得到的轨迹点的数量大于我们需要的数量就继续计算
        {
            tempPos.Clear();
            int tmepValue = 0;
            for(int i=0;i<tempNewList.Count-1; )
             {
                tmepValue++;
                int pointNums = tempNewList.Count / icount ;    
                 for (int j=1;j< pointNums; j++)
                 { 
                    Vector3 tempPoint = (tempNewList[i + j] - tempNewList[i+j-1]) / icount * tmepValue + tempNewList[i+j-1];
                    tempPos.Add(tempPoint);
                }
                i = i + pointNums;
            }
            return  ComputationalTrajectory(tempPos);
        }
        else    // 当得到的轨迹点的数量小于我们需要的数量时,进行初次计算
        {
            tempPos.Clear();
            for (int i = 0; i < icount; i++)
            {
                for (int j = 1; j < tempNewList.Count; j++)
                {
                    Vector3 tempPoint = (tempNewList[j] - tempNewList[j-1]) / icount * i + tempNewList[j-1];
                    tempPos.Add(tempPoint);
                }
            }          
            return ComputationalTrajectory(tempPos);
        }
    }   
}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值