unity_摄像机跟随

时间:2025-04-01 08:58:12
//挂载到摄像机上,当然可以不只是摄像机跟随 public class CameraFollow : MonoBehaviour { public Transform target; //目标物体 public Vector3 offset; //偏移 public float rotateSpeed=10f; //摄像机与target之间角度转换快慢 public float moveSpeed= 10f; //摄像机与target之间距离转换快慢 //通过使摄像机始终面向target public void LookAtTarget() { Vector3 vRot = target.position - this.transform.position; Quaternion qRot = Quaternion.LookRotation(vRot , Vector3.up); transform.rotation = Quaternion.Lerp(transform.rotation, qRot , rotateSpeed* Time.deltaTime); } //通过插值运算使摄像机朝target运动并保持距离 public void MoveToTarget() { Vector3 pos = target.position + target.forward * offset.z + target.right * offset.x + target.up * offset.y; transform.position = Vector3.Lerp(transform.position, pos, moveSpeed* Time.deltaTime); } //固定帧率刷新 public void FixedUpdate() { LookAtTarget(); MoveToTarget(); } }