using System.Collections; using System.Collections.Generic; using UnityEngine; //摄像机操作 //删减版 在实际的使用中可能会有限制的需求 比如最大远离多少 最近距离多少 不能旋转到地面以下等 public class BaseCam : MonoBehaviour { public static BaseCam Instance; /// /// 相机围绕的物体 /// public Transform CenObj;//围绕的物体 /// /// 旋转坐标 /// private Vector3 Rotation_Transform; private new Camera camera; private void Awake() { Instance = this; } void Start() { camera = GetComponent(); } void Update() { if (CenObj == null) return; Ctrl_Cam_Move(); Cam_Ctrl_Rotation(); } [ContextMenu("测试")] public void Test() { Init(CenObj); } public void Init(Transform CenObj) { camera.transform.position = new Vector3(0, 1, -10); camera.transform.eulerAngles = Vector3.zero; this.CenObj = CenObj; Rotation_Transform = CenObj.position; } Vector3 mouseDownPoint; float mouseCamPositionY; //镜头的远离和接近 public void Ctrl_Cam_Move() { if (Input.GetAxis("Mouse ScrollWheel") > 0) { transform.Translate(Vector3.forward * 0.1f);//速度可调 自行调整 } if (Input.GetAxis("Mouse ScrollWheel") < 0) { transform.Translate(Vector3.forward * -0.1f);//速度可调 自行调整 } /*优化移动方式*/ if (Input.GetKeyDown(KeyCode.Mouse2)) { mouseDownPoint = Input.mousePosition; mouseCamPositionY = transform.position.y; } if (Input.GetKey(KeyCode.Mouse2)) { var delta = Input.mousePosition - mouseDownPoint; var tra = transform.position; tra.y = mouseCamPositionY - delta.y * 0.001f; transform.position = tra; } } //摄像机的旋转 public void Cam_Ctrl_Rotation() { if (Input.GetKey(KeyCode.Mouse1)) { var mouse_x = Input.GetAxis("Mouse X");//获取鼠标X轴移动 var mouse_y = -Input.GetAxis("Mouse Y");//获取鼠标Y轴移动 transform.RotateAround(Rotation_Transform, Vector3.up, mouse_x * 5); transform.RotateAround(Rotation_Transform, transform.right, mouse_y * 5); } } }