using UnityEngine; using UnityEngine.UIElements; /// <summary> /// 鼠标控制摄像机环绕某点运动 /// </summary> public class CameraAroundController : MonoBehaviour { //环绕点 [SerializeField] private Transform aroundTransform; //摄像机 [SerializeField] private Transform cameraTransform; //旋转速度 [SerializeField] private float m_Speed = 5.0f; //鼠标滚轮灵敏度 [SerializeField] private float m_ScrollWheelSensitivity = 40f; //是否开启鼠标滚轮 [SerializeField] private bool m_ScrollWheelEnabled = true; private Vector3 lastPosition; public Transform AroundTransform { get { return aroundTransform; } set { aroundTransform = value; } } public Transform CameraTransform { get { return cameraTransform; } set { cameraTransform = value; } } void Update() { if (aroundTransform == null || cameraTransform == null) return; MouseRotation(); MouseScrollWheel(); } // 鼠标控制旋转 private void MouseRotation() { if (Input.GetMouseButtonDown(0)) { lastPosition = Input.mousePosition; return; } if (!Input.GetMouseButton(0)) return; if (UGUITool.IsPointerOverUI()) return; Vector3 mousePosition = Input.mousePosition; Vector3 offset = mousePosition - lastPosition; lastPosition = mousePosition; //绕X轴旋转角度 float angleX = -offset.y * Time.deltaTime * m_Speed; //绕Y轴旋转角度 float angleY = offset.x * Time.deltaTime * m_Speed; //绕X轴旋转四元数 Quaternion quaternionX = Quaternion.AngleAxis(angleX, cameraTransform.right); //绕Y轴旋转四元数 Quaternion quaternionY = Quaternion.AngleAxis(angleY, Vector3.up); //综合旋转四元数 Quaternion quaternion = quaternionX * quaternionY; //旋转向量到新的位置 Vector3 point = aroundTransform.position; Vector3 vector = cameraTransform.position; Vector3 vector2 = vector - point; vector2 = quaternion * vector2; Vector3 new_vector = point + vector2; //旋转前的方向向量 Vector3 before_forward = point - vector; //旋转后的方向向量 Vector3 after_forward = point - new_vector; //限制摄像机最小俯视视角为0度 float angle = Vector3.Angle(after_forward, Vector3.up); if (angle < 90)//小于90度将变成仰视角度 return; //将before_forward投影到z平面上 Vector3 zforward = before_forward; zforward.y = 0f; //限制摄像机最大俯视视角为90度 angle = Vector3.Angle(zforward, after_forward); if (angle > 90) return; cameraTransform.position = new_vector; cameraTransform.LookAt(point); } // 鼠标滚轮 private void MouseScrollWheel() { if (!m_ScrollWheelEnabled) return; float scrollWheel = Input.GetAxis("Mouse ScrollWheel"); if (scrollWheel == 0f) return; Vector3 direction = cameraTransform.position - aroundTransform.position; direction.Normalize(); cameraTransform.position -= direction * scrollWheel * m_ScrollWheelSensitivity; } }