Unity的Lerp函数实现缓动

下面例子实现点光源的移动在场景中创建好一个平面,一个点光源,我在这里随便放了一个模型。然后新建c#脚本,代码如下:using UnityEngine;using System.Collections;public class Lerp : MonoBehaviour { public Vector3 newPos; // Use this for initialization void Start () { newPos = transform.position; } // Update is called once per frame void Update () { if(Input.GetKeyDown(KeyCode.Q)) newPos = new Vector3(-3,8,22); if(Input.GetKeyDown(KeyCode.E)) newPos = new Vector3(3,8,22); transform.position = Vector3.Lerp(transform.position,newPos,Time.deltaTime); }}  然后将脚本拖动到点光上面,按下键盘Q和E键就可以看到效果了。上面是用Vector3的Lerp函数进行缓动的。里面的参数是(Vector3 from,Vector3 to,float time);比如我们想改变light的颜色或者强度intensity,那么参数是2个浮点数,我们就可以用Mathf.Lerp(float from,float to,float time)进行缓动了。
如果你想自定义一个缓动方法,可以使用委托和 Lambda 表达式来实现。下面是一个自定义的缓动方法示例: ```csharp using UnityEngine; using System; public class CustomEasing : MonoBehaviour { private Vector3 start; private Vector3 end; private float duration; private Action<Vector3> onValueChanged; public void StartTween(Vector3 start, Vector3 end, float duration, Action<Vector3> onValueChanged) { this.start = start; this.end = end; this.duration = duration; this.onValueChanged = onValueChanged; StartCoroutine(Tween()); } private IEnumerator Tween() { float t = 0f; while (t < duration) { t += Time.deltaTime; float p = t / duration; Vector3 value = Vector3.Lerp(start, end, EasingFunction(p)); onValueChanged?.Invoke(value); yield return null; } onValueChanged?.Invoke(end); } private Func<float, float> EasingFunction = p => p; // 默认为线性缓动 public void SetEasingFunction(Func<float, float> easingFunction) { EasingFunction = easingFunction; } } ``` 上面的代码中,我们定义了一个 CustomEasing 类,它包含了一个 StartTween 方法和一个 SetEasingFunction 方法。StartTween 方法用于启动缓动,它需要传入起始值、结束值、缓动时间和回调函数,回调函数将在每一帧更新缓动值。SetEasingFunction 方法用于设置缓动函数缓动函数是一个委托,它接受一个参数 t,表示缓动进度,返回一个缓动值。 在 StartTween 方法中,我们使用 StartCoroutine 方法启动了一个协程,在协程中不断更新缓动值,并在每一帧调用回调函数缓动值的计算使用了 Mathf.Lerp 方法和缓动函数。最后,在缓动结束时,我们调用了回调函数,将最终值传递出去。 使用时,你可以先创建一个 CustomEasing 对象,然后使用 SetEasingFunction 方法设置缓动函数,最后使用 StartTween 方法启动缓动。例如,下面是一个使用弹性缓动的示例: ```csharp CustomEasing easing = new CustomEasing(); easing.SetEasingFunction(p => Mathf.Sin(p * Mathf.PI * (0.2f + 2.5f * p * p * p)) * Mathf.Pow(1f - p, 2.2f) + p); easing.StartTween(Vector3.zero, Vector3.one, 1f, value => transform.position = value); ``` 在这个示例中,我们先创建了一个 CustomEasing 对象,并使用 SetEasingFunction 方法设置了弹性缓动函数。然后,我们调用 StartTween 方法启动缓动,将起始值、结束值、缓动时间和回调函数传递进去。回调函数中将更新物体的位置。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值