自己使用的是 Unity和VS版。
向主相机添加FollowPlayer类。
下面呈现代码
这里有小Bug, 拉近拉远和旋转视角无法同时使用,后续会进行更改完善
public class FollowPlayer : MonoBehaviour {private Transform player;//主角 随便创建一个物体 将它的标签改为Playerprivate Vector3 offsetPosition;//位置偏移public float distance = 0;public float scrollSpeed = 10;//拉近缩小的速度public float rotateSpeed = 10;private bool isRotaing = false;// Use this for initializationvoid Start () {player = GameObject.FindGameObjectWithTag(tags.player).transform;transform.LookAt(player.position);offsetPosition = transform.position - player.position;}// Update is called once per framevoid Update () {transform.position = offsetPosition + player.position;//处理视野的拉近和拉远效果ScrollUV();//处理视野的旋转RotateView();}//🐂🍺void ScrollUV(){//print(Input.GetAxis("Mouse ScrollWheel"));//向后滑动返回负值(拉远视野) 向前滑动返回正值(拉近视野)distance = offsetPosition.magnitude;distance -= Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;//个人习惯是向后为拉远 所以减去滚筒所得数distance = Mathf.Clamp(distance,2, 18);//限制拉近拉远的距离offsetPosition = offsetPosition.normalized * distance;//方向不变长度变为distance}void RotateView(){//Input.GetAxis("Mouse X");//得到鼠标在水平方向的滑动//Input.GetAxis("Mouse Y");//得到鼠标在数值方向的滑动if (Input.GetMouseButtonDown(1)){isRotaing = true;}if (Input.GetMouseButtonUp(1)){isRotaing = false;}if (isRotaing){transform.RotateAround(player.position,player.up, rotateSpeed * Input.GetAxis("Mouse X"));Vector3 originaIPOS = transform.position;Quaternion originaIRotation = transform.rotation;transform.RotateAround(player.position,transform.right,-rotateSpeed * Input.GetAxis("Mouse Y"));//影响的属性有两个 一个是position 一个是 rotationfloat x = transform.eulerAngles.x;if (x < 10 || x > 80)//超出范围 我们将归回原位 旋转无效{transform.position = originaIPOS;transform.rotation = originaIRotation;}x = Mathf.Clamp(x, 10, 80);transform.eulerAngles = new Vector3(x, transform.eulerAngles.y, transform.eulerAngles.z);}offsetPosition = transform.position - player.position;}}
添加标签步骤
后续会完善,感谢各位大佬捧场