固定跟随(不带旋转)
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public Transform target;//目标物体
public float smoothing = 3;//平滑系数
void LateUpdate ()
{
//目标物体要到达的目标位置 = 当前物体的位置 + 当前摄像机的位置
Vector3 targetPos = target.position + new Vector3 (0, 9, -10);
//使用线性插值计算让摄像机用smoothing * Time.deltaTime时间从当前位置到移动到目标位置
this.transform.position = Vector3.Lerp (this.transform.position, targetPos, smoothing * Time.deltaTime);
}
}
固定跟随(带旋转)
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public Transform target;//目标物体
public float smoothing = 3;//平滑系数
void LateUpdate ()
{
//目标物体要到达的目标位置 = 当前物体的位置 + 当前摄像机的位置
Vector3 targetPos = target.position + new Vector3 (0, 9, -10);
//使用线性插值计算让摄像机用smoothing * Time.deltaTime时间从当前位置到移动到目标位置
this.transform.position = Vector3.Lerp (this.transform.position, targetPos, smoothing * Time.deltaTime);
//使用Quaternion.LookRotation方法可以计算出目标位置旋转后相机需要旋转的角度
Quaternion angle = Quaternion.LookRotation (target.position - this.transform.position);
//使用球形差值计算可以得到从当前的位置旋转到移动后的位置
this.transform.rotation = Quaternion.Slerp (this.transform.rotation, angle, smoothing * Time.deltaTime);
}
}
第三人称跟随
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public Transform target;//目标物体
public float distance = 10;//距离
public float height = 5;//高度
public float heightDamping = 2;//高度的阻尼系数
public float rotationDamping = 3;//旋转的阻尼系数
void LateUpdate()
{
//如果场景中有Player物体
if (GameObject.FindWithTag ("Player")) {
//如果目标物体为空
if (!target)
//重新取得目标物体
target = GameObject.FindWithTag ("Player").transform;
//摄像机最终旋转的角度
float wantedRotationAngle = target.eulerAngles.y;
//摄像机最终的高度
float wantedHeight = target.position.y + height;
//摄像机当前的角度
float currentRotationAngle = transform.eulerAngles.y;
//摄像机当前的高度
float currentHeight = transform.position.y;
currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);
//相机当前的旋转
Quaternion currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);
//相机的实际位置 = 目标位置 - 相机当前的正方向位置*距离
Vector3 pos = target.position - currentRotation * Vector3.forward * distance;
//相机实际位置的高度
pos.y = currentHeight;
//最后把实际位置赋值给相机
transform.position = pos;
//摄像机始终朝向目标位置
transform.LookAt (target);
}
}
}
未完待续