因为学这部分知识的时候不是很懂,所以把自己的理解写下来,如有错误欢迎指正。
首先,Mathf.Lerp()方法的参数为三个浮点数,如图:
通过f12可以查看这个方法的实现。如图:
其实就是只要输入0-1之间的值,Lerp方法返回a+(a-b)*t。
我们不妨定义一个浮点数start作为起始值,result为结果。
用法一.
每帧改变start的值,那么变化速度先快后慢,与第二个参数的差最终会无限趋近于0。
例如:每一帧都执行:start=Mathf.Lerp(start,10,t)
每一帧都改变start,即每一帧都令start=start+(10-start)*t
因为start每帧更新,所以当start接近与10的时候,每一帧的变化会越来越小。具体的证明可以求导,我这里就不写了。
用法二.
每帧改变t的值使线性增长。
可以用一个float变量time当计时器。
每一帧,令time+=Time.deltaTime
然后,令result=Mathf.Lerp(start,10,time)
每一帧的result=start+(10-start)*time
不妨令result=y,time=x;
可以看出x显然随时间线性增长,y=(10-start)*x+start,因为这里并没有每帧更新start,所以start是常量,所以y是关于x的一次函数,线性增长。
如果我们要使用Lerp方法实现一个物体跟随另一个物体
方法一:效果:在接近时减小速度
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lesson1_Mathf : MonoBehaviour
{
//要追踪的目标位置
public Transform target;
//本物体的位置
public Vector3 pos;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
pos = transform.position;
pos.x=Mathf.Lerp(pos.x,target.position.x,Time.deltaTime);
pos.y=Mathf.Lerp(pos.y,target.position.y,Time.deltaTime);
pos.z=Mathf.Lerp(pos.z,target.position.z,Time.deltaTime);
transform.position = pos;
}
}
方法二:效果,匀速接近
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lesson1_Mathf : MonoBehaviour
{
//要追踪的目标
public Transform target;
//目标当前位置
public Vector3 targetNowPos;
//物体的开始位置
public Vector3 startPos;
//物体的当前位置
public Vector3 pos;
//计时器
public float time = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
time += Time.deltaTime;
if(targetNowPos!=target.position)
{
//只要目标移动,起始位置,目标位置,计时器都要重置(不懂的去看博客上面方法二的分析)
time = 0;
targetNowPos = target.position;
startPos=transform.position;
}
pos=this.transform.position;
pos.x = Mathf.Lerp(startPos.x, targetNowPos.x, time);
pos.y= Mathf.Lerp(startPos.y, targetNowPos.y, time);
pos.z= Mathf.Lerp(startPos.z, targetNowPos.z, time);
transform.position = pos;
}
}
第一种比较简单,第二种方法难点就是要记得在每次目标移动的时候,重置各个参数。
那就这样。