首先介紹一下Vector3.Lerp(Vector a, Vector b, float t)方法,這是一個向量插值方法,t的取值範圍是0-1,t向0靠近,傳回值向a靠近;t向1靠近,傳回值向b靠近。
下面對Lerp的傳回值和t的值關系進行測試
測試代碼:
Vector3 v1 = new Vector3(, , );
Vector3 v2 = new Vector3(, , );
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 = f; //平滑量
Vector3 distance;
void Start()
{
distance = transform.position - target.position; //target到camera的距離
}
void Update()
{
transform.position = Vector3.Lerp(transform.position, target.position + distance, smooth);
}
}