开源项目工具:LeanTween - 为Unity 3D打造的高效缓动引擎详解(比较麻烦的API版)——实现物体抛物线移动
为了让LeanTween更具有灵活性,LeanTween开放了一个API:
LeanTween.value(gameObject,回调函数,起始数值,终点数值,时间)
API中的数值,可以是float,vector3,vector2,color等类型
所以可以用回调函数做很多事情,比如可以同时对物体的大小和位置进行调整。
以下直接上代码,实现物体的抛物线运动:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
using UnityEngine.UI;
public class 测试抛物线 : MonoBehaviour
{
[Header("目标点")]
public GameObject target;
[Header("开始按钮")]
public Button btn_begin;
[Header("暂停按钮")]
public Button btn_end;
[Header("恢复按钮")]
public Button btn_resume;
[Header("重置按钮")]
public Button btn_restore;
[Header("LeanTwee唯一ID")]
public int _id;
[Header("抛物线高度")]
public float parabolaHeight;
private Vector3 oriPos;//起始坐标
// Start is called before the first frame update
void Start()
{
oriPos = transform.position;
btn_begin.onClick.AddListener(() => {
Action<Vector3> updatePos = UpdatePos;
_id = LeanTween.value(gameObject, updatePos, transform.position, target.transform.position, 5f).id;
});
btn_end.onClick.AddListener(() => {
LeanTween.pause(_id);
});
btn_resume.onClick.AddListener(() => {
LeanTween.resume(_id);
});
btn_restore.onClick.AddListener(() => {
transform.position = oriPos;
});
}
private void UpdatePos(Vector3 pos)
{
float ratio = Vector3.Distance(pos, oriPos) / Vector3.Distance(target.transform.position, oriPos);
Vector3 currentPos = pos;
currentPos.y += Mathf.Sin(ratio * Mathf.PI) * parabolaHeight;
transform.position = currentPos;
}
}
代码很简单!
PS:
注意:
如果同时加添加多种动画,比如:
LeanTween.value(gameObject, UpdatePosCall, transform.position, target.transform.position, 5f)
.setOnUpdate(OnOtherThing)
.setEase(LeanTweenType.easeInElastic).setLoopClamp(1);
这时候如果用setOnUpdate控制动画细节可能会出现问题,所以这时候最好将动画细节控制放到回调函数UpdatePosCall中,大家可以多试试,交流