前言:实际项目开发过程中过,我们经常会使用到:Vector3.Lerp ()、Mathf.Lerp() …等方法。而此类方法返回的值其实是线性增长。但很多朋友却做成了弹性增长,甚至不曾知晓。
一、创建相应的对象。
1.创建两个Cube,分别命名为Cube_One、Cube_Two.
2.创建地面Plane。
3.图示
二、创建脚本 “LerpStudy.cs”
1.脚本示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LerpStudy : MonoBehaviour
{
/// <summary>
/// 目标位置
/// </summary>
private Vector3 m_Target;
/// <summary>
/// 方式一常用的 速度表达方式
/// </summary>
private float m_Speed = 2.0f;
/// <summary>
/// 当前选择的运行方法
/// </summary>
public MethodType CurrMethodType;
/// <summary>
/// 方式一常用的 时间累加表达方式
/// </summary>
private float m_Time;//时间
private void Awake()
{
m_Target = new Vector3(transform.position.x, 0.0f, 10.0f);
}
private void Start()
{ }
private void Update()
{
if (CurrMethodType == MethodType.One)
{
Method_One();
}
else
{
Method_Two();
}
}
/// <summary>
/// 错误的使用方式
/// </summary>
private void Method_One()
{
transform.position = Vector3.Lerp(transform.position, m_Target, Time.deltaTime * m_Speed);
}
/// <summary>
/// 正确的使用方式
/// </summary>
private void Method_Two()
{
m_Time = Time.deltaTime + m_Time;
transform.position = Vector3.Lerp(transform.position, m_Target, m_Time * 0.05f);
}
}
/// <summary>
/// 方法类型
/// </summary>
public enum MethodType
{
One,
Two
}
2.脚本中有Method_One() 和 Method_Two()方法。Method_One()是大家常用的并且错误的使用方式,Method_Two()是正确的使用方式。
3.将脚本分别挂载到Cube_One和Cube_Two上,并且Cube_One的MethodType选择One,Cube_Two的MethodType选择Two。
4.运行结果如下:
5.分析可以明显的看出上方的cube弹性速度到达目标位置,而下方的cube则是匀速的。
紧记公式:value = a + (b - a) * t;
a是当前位置
b是目标位置
t是百分比增加,取值为0~1之间(可以用时间增量)