首先介绍一下Vector3.Lerp(Vector a, Vector b, float t)方法,这是一个向量插值方法,t的取值范围是0-1,t向0靠近,返回值向a靠近;t向1靠近,返回值向b靠近。
下面对Lerp的返回值和t的值关系进行测试
测试代码:
Vector3 v1 = new Vector3(0, 0, 0);
Vector3 v2 = new Vector3(10, 10, 10);
Debug.Log(Vector3.Lerp(v1, v2, smooth));
测试过程:
smooth = -10 —> 输出:(0.0, 0.0, 0.0)
smooth = 0 —> 输出: (0.0, 0.0, 0.0)
smooth = 0.1 —> 输出:(1.0, 1.0, 1.0)
smooth = 0.2 —> 输出: (2.0, 2.0, 2.0)
…
smooth = 0.9 —> 输出: (9.0, 9.0, 9.0)
smooth = 1 —> 输出:(10.0, 10.0, 10.0)
smooth = 10 —> 输出: (10.0, 10.0, 10.0)
总结:
当0 <= t <= 1时,Lerp返回值为:a * (1-t) + b * t
当t > 1时,Lerp的返回值为: b
当t < 0时,Lerp的返回值为: a
实现摄像头跟随物体移动:
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public Transform target; //camera的跟随目标
public float smooth = 0.5f; //平滑量
Vector3 distance;
void Start()
{
distance = transform.position - target.position; //target到camera的距离
}
void Update()
{
transform.position = Vector3.Lerp(transform.position, target.position + distance, smooth);
}
}