Unity中实现通过鼠标对物体进行旋转平移缩放

1|0废话不多说,直接上代码 —— 将下面的代码赋给所需要控制的物体上即可。

using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseControlModel : MonoBehaviour { //旋转最大角度 public int yMinLimit = -20; public int yMaxLimit = 80; //旋转速度 public float xSpeed = 250.0f; public float ySpeed = 120.0f; //旋转角度 private float x = 0.0f; private float y = 0.0f; void Update() { if (Input.GetMouseButton(0)) { //将屏幕坐标转化为世界坐标 ScreenToWorldPoint函数的z轴不能为0,不然返回摄像机的位置,而Input.mousePosition的z轴为0 //z轴设成10的原因是摄像机坐标是(0,0,-10),而物体的坐标是(0,0,0),所以加上10,正好是转化后物体跟摄像机的距离 Vector3 temp = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10)); transform.position = temp; } else if (Input.GetMouseButton(1)) { //Input.GetAxis("MouseX")获取鼠标移动的X轴的距离 x += Input.GetAxis("Mouse X") * xSpeed * 0.02f; y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f; y = ClampAngle(y, yMinLimit, yMaxLimit); //欧拉角转化为四元数 Quaternion rotation = Quaternion.Euler(y, x, 0); transform.rotation = rotation; } else if (Input.GetAxis("Mouse ScrollWheel") != 0) { //鼠标滚动滑轮 值就会变化 if (Input.GetAxis("Mouse ScrollWheel") < 0) { //范围值限定 if (Camera.main.fieldOfView <= 100) Camera.main.fieldOfView += 2; if (Camera.main.orthographicSize <= 20) Camera.main.orthographicSize += 0.5F; } //Zoom in if (Input.GetAxis("Mouse ScrollWheel") > 0) { //范围值限定 if (Camera.main.fieldOfView > 2) Camera.main.fieldOfView -= 2; if (Camera.main.orthographicSize >= 1) Camera.main.orthographicSize -= 0.5F; } } } //角度范围值限定 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); } }

__EOF__

本文作者艾孜尔江
本文链接https://www.cnblogs.com/ezhar/p/13261871.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   艾孜尔江  阅读(1440)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示