1 using UnityEngine; 2 using System.Collections; 3 4 public class CameraFllow : MonoBehaviour { 5 6 private Transform player; 7 public float speed = 3; 8 9 void Start() 10 { 11 //向服务器实时更新数据的时候 将Player信息也更新 12 player = GameDataUtil.playerModel.transform; 13 } 14 15 void Update() 16 { 17 //由 摄像机 和 玩家固定距离偏量 构建插值 18 Vector3 targetPos = player.position + new Vector3(0.28f,20.56f,60f); 19 //移动 20 transform.position = Vector3.Lerp(transform.position , targetPos , speed * Time.deltaTime); 21 //角度的移动 lookRotation 是按向量变换时的长度 来变的 ,相减 是由相机位置指向玩家 22 Quaternion targetRotation = Quaternion.LookRotation(player.position - transform.position); 23 // Slerp是根据 变换过程中角度的变化 插值的 24 transform.rotation = Quaternion.Slerp(transform.rotation , targetRotation , speed * Time.deltaTime); 25 } 26 }
1 using UnityEngine; 2 using System.Collections; 3 4 public class FollowPlayer : MonoBehaviour { 5 6 private Transform player; 7 private Vector3 offsetPosition;//位置偏移 8 private bool isRotating = false; 9 10 11 public float distance = 0; 12 public float scrollSpeed = 10; 13 public float rotateSpeed = 2; 14 15 // Use this for initialization 16 void Start () { 17 player = GameObject.FindGameObjectWithTag(Tags.player).transform; 18 transform.LookAt(player.position); 19 offsetPosition = transform.position - player.position; 20 } 21 22 // Update is called once per frame 23 void Update () { 24 transform.position = offsetPosition + player.position; 25 //处理视野的旋转 26 RotateView(); 27 //处理视野的拉近和拉远效果 28 ScrollView(); 29 } 30 31 void ScrollView() { 32 //print(Input.GetAxis("Mouse ScrollWheel"));//向后 返回负值 (拉近视野) 向前滑动 返回正值(拉远视野) 33 distance = offsetPosition.magnitude; 34 distance += Input.GetAxis("Mouse ScrollWheel")*scrollSpeed; 35 distance = Mathf.Clamp(distance, 2, 18); 36 offsetPosition = offsetPosition.normalized * distance; 37 } 38 39 void RotateView() { 40 //Input.GetAxis("Mouse X");//得到鼠标在水平方向的滑动 41 //Input.GetAxis("Mouse Y");//得到鼠标在垂直方向的滑动 42 if (Input.GetMouseButtonDown(1)) { 43 isRotating = true; 44 } 45 if (Input.GetMouseButtonUp(1)) { 46 isRotating = false; 47 } 48 49 if (isRotating) { 50 transform.RotateAround(player.position,player.up, rotateSpeed * Input.GetAxis("Mouse X")); 51 52 Vector3 originalPos = transform.position; 53 Quaternion originalRotation = transform.rotation; 54 55 transform.RotateAround(player.position,transform.right, -rotateSpeed * Input.GetAxis("Mouse Y"));//影响的属性有两个 一个是position 一个是rotation 56 float x = transform.eulerAngles.x; 57 if (x < 10 || x > 80) {//当超出范围之后,我们将属性归位原来的,就是让旋转无效 58 transform.position = originalPos; 59 transform.rotation = originalRotation; 60 } 61 62 } 63 64 offsetPosition = transform.position - player.position; 65 } 66 }