Unity贝塞尔曲线和DOTween联合使用动画方案

背景

开发过程中有时会用到做贝塞尔曲线动画,单单有DoTween有时候达不到效果,此时可以采用此方案解决。扩展下,可以通过更换控制点,随机更多曲线动画。

核心代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class TestBezier : MonoBehaviour
{
     
    private float _times=3f;
    private float _pointCount = 5f;
    public GameObject obj;
    public GameObject startObj;
    public GameObject controlObj;
    public GameObject endObj;
   
    // Update is called once per frame
    void Update()
    {
     
        if (Input.GetKeyDown(KeyCode.A))
        {
     
            DoAnim();
        }
    }
    private void DoAnim()
    {
     
        obj.transform.position = startObj.transform.position;
        Vector3[] pathvec = Bezier2Path(startObj.transform.position, controlObj.transform.position, endObj.transform.position);
        obj.transform.DOPath(pathvec, _times);
    }
    //获取二阶贝塞尔曲线路径数组
    private  Vector3[] Bezier2Path(Vector3 startPos, Vector3 controlPos, Vector3 endPos)
    {
     
        Vector3[] path = new Vector3[(int)_pointCount];
        for (int i = 1; i <= _pointCount; i++)
        {
     
            float t = i / _pointCount;
            path[i - 1] = Bezier2(startPos, controlPos, endPos, t);
        }
        return path;
    }
    // 2阶贝塞尔曲线
    public static Vector3 Bezier2(Vector3 startPos, Vector3 controlPos, Vector3 endPos, float t)
    {
     
        return (1 - t) * (1 - t) * startPos + 2 * t * (1 - t) * controlPos + t * t * endPos;
    }

    // 3阶贝塞尔曲线
    public static Vector3 Bezier3(Vector3 startPos, Vector3 controlPos1, Vector3 controlPos2, Vector3 endPos, float t)
    {
     
        float t2 = 1 - t;
        return t2 * t2 * t2 * startPos
            + 3 * t * t2 * t2 * controlPos1
            + 3 * t * t * t2 * controlPos2
            + t * t * t * endPos;
    }
}

可参考以下链接理解贝塞尔曲线和公式:
https://blog.csdn.net/cfan927/article/details/104649623/
https://blog.csdn.net/weixin_42513339/article/details/83019610

你可能感兴趣的:(Unity,Unity,贝塞尔曲线,曲线动画,DoTween和贝塞尔曲线)