using UnityEngine; public class MoveCameraByMouse : MonoBehaviour { public static MoveCameraByMouse instance; [Header("设置初始视角")] public Vector3 initialPosition = new Vector3(376f, 565f, 155f); public Vector3 initialRotation = new Vector3(58.3f, -90f, 0f); [Header("围绕旋转的目标物体")] public Transform target; [Header("是否开启旋转")] public bool ison = true; [Header("设置旋转角度")] public float x = 154.6f, y = 31.5f, z = 0f; [Header("旋转速度值")] public float xSpeed = 100, ySpeed = 100; [Header("缩放速度值")] public float mSpeed = 2; [Header("y轴角度限制,设置成一样则该轴不旋转")] public float yMinLimit = -365, yMaxLimit = 365; [Header("x轴角度限制")] public float leftMax = -365, rightMax = 365; [Header("距离限制")] public float distance = 7f, minDistance = 0.1f, maxDistance = 10f; [Header("阻尼设置")] public bool needDamping = true; public float damping = 3f; [Header("是否正在旋转")] public bool isRotate; [Header("是否正在缩放")] public bool isZoom; private void Start() { instance = this; transform.position = initialPosition; transform.rotation = Quaternion.Euler(initialRotation); } public void LateUpdate() { if (target && ison == true) { if (Input.GetMouseButton(0)) { isRotate = true; // 判断是否需要反向旋转 if ((y > 90f && y < 270f) || (y < -90 && y > -270f)) { x -= Input.GetAxis("Mouse X") * xSpeed * 0.02f; } else { x += Input.GetAxis("Mouse X") * xSpeed * 0.02f; } y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f; x = ClampAngle(x, leftMax, rightMax); y = ClampAngle(y, yMinLimit, yMaxLimit); } else isRotate = false; if (Input.GetAxis("Mouse ScrollWheel") != 0) { isZoom = true; } else isZoom = false; distance -= Input.GetAxis("Mouse ScrollWheel") * mSpeed; distance = Mathf.Clamp(distance, minDistance, maxDistance); Quaternion rotation = Quaternion.Euler(y, x, z); Vector3 disVector = new Vector3(0.0f, 0.0f, -distance); Vector3 position = rotation * disVector + target.position; // 阻尼感 if (needDamping) { transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * damping); transform.position = Vector3.Lerp(transform.position, position, Time.deltaTime * damping); } else { transform.rotation = rotation; transform.position = position; } } } // 对数值进行限制; static float ClampAngle(float angle, float min, float max) { if (angle < -360) angle += 360; if (angle > 360) angle -= 360; return Mathf.Clamp(angle, min, max); } }