鼠标控制相机绕目标点旋转,远近拉近
代码如下:
1 public class CameraController :SingletonMono<CameraController> 2 { 3 [Header("目标位置")] 4 public Transform target; 5 [Header("旋转X轴")] 6 public float mouse_x = 0; 7 [Header("旋转Y轴")] 8 public float mouse_y = 0; 9 [Header("X轴最小旋转值")] 10 public float xMinLimit; 11 [Header("X轴最大旋转值")] 12 public float xMaxLimit; 13 [Header("摄像机与目标点距离")] 14 public float distance; 15 [Header("摄像机与目标点最大距离")] 16 public float maxDistance; 17 [Header("摄像机与目标点最小距离")] 18 public float minDistance; 19 private float mouseWheelSensitivity=500;//鼠标灵敏度 20 21 private void Start() 22 { 23 //初始化相机位置 24 Vector3 angles = transform.eulerAngles;//获取自身rotation 25 mouse_y = angles.y; 26 mouse_x = angles.x; 27 } 28 private void LateUpdate() 29 { 30 if (Input.GetMouseButton(1)) //按下鼠标右键 31 { 32 mouse_y += Input.GetAxis("Mouse X")*4; 33 mouse_x -= Input.GetAxis("Mouse Y")*4 ; 34 mouse_x = ClampAngle(mouse_x, xMinLimit, xMaxLimit); 35 } 36 else if (Input.GetAxis("Mouse ScrollWheel") != 0) //鼠标滚轮缩放功能 37 { 38 distance -= Input.GetAxis("Mouse ScrollWheel") * mouseWheelSensitivity; 39 distance = Mathf.Clamp(distance, minDistance, maxDistance); 40 } 41 if (mouse_x <= 1) //保证鼠标在地图上方 42 { 43 mouse_x = 1; 44 } 45 Quaternion Rotation= Quaternion.Euler(mouse_x, mouse_y, 0); 46 Vector3 disVector = new Vector3(0.0f, 0.0f, -distance); 47 Vector3 position = Rotation * disVector + target.position; 48 49 transform.rotation = Quaternion.Lerp(transform.rotation, Rotation, Time.deltaTime * 5); 50 transform.position = Vector3.Lerp(transform.position, position, Time.deltaTime * 5); 51 } 52 53 static float ClampAngle(float angle, float min, float max) 54 { 55 if (angle < -360) 56 angle += 360; 57 if (angle > 360) 58 angle -= 360; 59 return Mathf.Clamp(angle, min, max); 60 } 61 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?