using UnityEngine; using System; public class PanoramicCamera : MonoBehaviour { [Header("旋转设置")] public float rotateSpeed = 20f; public bool autoRotate = false; public float autoRotateSpeed = 10f; [Header("缩放设置")] public float zoomSpeed = 2f; public float minFOV = 30f; public float maxFOV = 90f; [Header("阻尼")] public float dampingFactor = 0.1f; // 阻尼系数,越小越平滑 public float rotationSmoothTime = 0.1f; // 平滑时间 private Camera cam; private float currentRotationX; private float currentRotationY; private Vector3 lastMousePosition; private bool isDragging = false; private bool isDisabled = false; private int revert = -1; private float targetRotationX; private float targetRotationY; private float rotationVelocityX; // 用于SmoothDamp private float rotationVelocityY; // 用于SmoothDamp void Start() { cam = GetComponent(); // 设置初始FOV cam.fieldOfView = 60f; // 获取摄像机的初始旋转角度 Vector3 initialRotation = cam.transform.eulerAngles; currentRotationX = initialRotation.y; currentRotationY = initialRotation.x; targetRotationX = currentRotationX; targetRotationY = currentRotationY; } void Update() { if (isDisabled) { return; } HandleInput(); if (autoRotate && !isDragging) { AutoRotate(); } // 平滑旋转 SmoothRotation(); } public void setIsDisabled(int value) { isDisabled = Convert.ToBoolean(value); } void HandleInput() { // 鼠标拖动控制 if (Input.GetMouseButtonDown(0)) { isDragging = true; lastMousePosition = Input.mousePosition; } else if (Input.GetMouseButtonUp(0)) { isDragging = false; } if (isDragging) { Vector3 delta = Input.mousePosition - lastMousePosition; // 更新目标旋转(目标值) targetRotationX += delta.x * rotateSpeed * Time.deltaTime; targetRotationY -= delta.y * rotateSpeed * Time.deltaTime; // 限制垂直旋转 targetRotationY = Mathf.Clamp(targetRotationY, -80f, 80f); lastMousePosition = Input.mousePosition; } // 滚轮缩放 float scroll = Input.GetAxis("Mouse ScrollWheel"); if (scroll != 0) { float newFOV = cam.fieldOfView - scroll * zoomSpeed; cam.fieldOfView = Mathf.Clamp(newFOV, minFOV, maxFOV); } } void AutoRotate() { targetRotationX += autoRotateSpeed * Time.deltaTime; } void SmoothRotation() { // 使用SmoothDamp平滑旋转 currentRotationX = Mathf.SmoothDamp(currentRotationX, targetRotationX, ref rotationVelocityX, rotationSmoothTime); currentRotationY = Mathf.SmoothDamp(currentRotationY, targetRotationY, ref rotationVelocityY, rotationSmoothTime); // 应用平滑后的旋转 transform.rotation = Quaternion.Euler(revert * currentRotationY, revert * currentRotationX, 0); } }