Unity中使用Vector3.SmoothDamp(平滑阻尼)方法进行跟随移动,可以使跟随看起来很平滑,而不显得突兀,最典型的示例就是相机平滑跟随角色移动。
static function SmoothDamp (current : Vector3, target : Vector3, ref currentVelocity : Vector3, smoothTime : float, maxSpeed : float = Mathf.Infinity, deltaTime : float = Time.deltaTime) : Vector3
各参数含义:
1.current 当前物体位置
2.target 目标物体位置
3.ref currentVelocity 当前速度,这个值由你每次调用这个函数时被修改(注:ref 关键字指参数按引用传递, 按引用传递的效果是,对所调用方法中参数进行的任何更改都反映在调用方法中。)
4.smoothTime 到达目标的时间,较小的值将快速到达目标
5.maxSpeed 所允许的最大速度,默认无穷大
6.deltaTime 自上次调用这个函数的时间,默认为Time.deltaTime
相机跟随角色移动的示例代码:
public class FllowTarget : MonoBehaviour {
public Transform charactor;//目标点的参考点
private float smoothTime = 0.01f;//移动所需的时间,值越小越快移动到目标处
private Vector3 currentVelocity=Vector3.zero;//当前速度,这个值每次调用SmoothDamp这个函数时被修改
private Camera mainCamera;//挂载的相机
void Awake () {
mainCamera = Camera.main;//初始化
}
void Start(){
charactor=GameObject.Find("Player").GetComponent<Transform>();//查找到对象名为“Player”的物体获取其上的Transform组件
void Update () {
//SmoothDamp方法的调用:在smoothTime时间内从当前点以当前速度移动到目标点
transform.position=Vector3.SmoothDamp(transform.position, charactor.position + new Vector3(0, 1, -10),ref currentVelocity, smoothTime);
}
}
上述示例的目标点为 charactor.position + new Vector3(0, 1, -10),即角色的后上方而不是角色位置处;charactor是public类型的,可以从Unity界面将角色物体直接拖拽指定,也可以在脚本中获取。