Unity DoTween 自定义曲线运动
对于很多不想写贝塞尔曲线或者不会写贝塞尔曲线的人来说,如果你恰好项目中用到DoTween,那么可以使用Unity+DoTween的组合方便快捷的实现曲线运动的功能。
废话不多说,上代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class TestMoves : MonoBehaviour
{
Vector3[] path1 = new Vector3[5];
[Header("终点")]
public GameObject Target;
Tweener tweenPath;
[Header("曲线点1")]
public GameObject tag1;
[Header("曲线点2")]
public GameObject tag2;
[Header("曲线点3")]
public GameObject tag3;
[Header("起点到终点的总时间")]
public float speed;
[Header("延迟多少秒开始")]
public float times;
Vector3 pos;
// Start is called before the first frame update
void Start()
{
pos = this.transform.position;
StartCoroutine(StayFuction());
}
IEnumerator StayFuction()
{
yield return new WaitForSeconds(times);
path1[0] = this.transform.position;//起始点
path1[1] = tag1.transform.position;
path1[2] = tag2.transform.position;
path1[3] = tag3.transform.position;
path1[4] = Target.transform.position;//终点
tweenPath = this.transform.DOPath(path1, speed, PathType.CatmullRom).SetLoops(-1, LoopType.Restart).SetEase(Ease.Linear);
}
//private void OnGUI()
//{
// if (GUI.Button(new Rect(10, 20, 120, 30), "重新运行"))
// {
// this.transform.position = pos;
// tweenPath.Kill();
// StopAllCoroutines();
// StartCoroutine(StayFuction());
// }
//}
}
使用的时候可以把注释打开,方便调试
代码没有注释,核心就是创建N个点,组成Dopath。
SetLoops(-1, LoopType.Restart) 循环类型我设置的Restart,一直循环,可以自己换。
SetEase(Ease.Linear) 移动类型,线性移动。