unity3d 第一人称脚本解释MouseLook
2015-02-03 11:51 糯米粥 阅读(1399) 评论(0) 编辑 收藏 举报1 using UnityEngine; 2 using System.Collections; 3 4 /// MouseLook rotates the transform based on the mouse delta. 5 /// Minimum and Maximum values can be used to constrain the possible rotation 6 7 /// To make an FPS style character: 8 /// - Create a capsule. 9 /// - Add the MouseLook script to the capsule. 10 /// -> Set the mouse look to use LookX. (You want to only turn character but not tilt it) 11 /// - Add FPSInputController script to the capsule 12 /// -> A CharacterMotor and a CharacterController component will be automatically added. 13 14 /// - Create a camera. Make the camera a child of the capsule. Reset it's transform. 15 /// - Add a MouseLook script to the camera. 16 /// -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.) 17 [AddComponentMenu("Camera-Control/Mouse Look")] 18 public class MouseLook : MonoBehaviour { 19 //3个枚举 20 // 这个表示当前控制模式,分别是 21 // MouseXAndY上下左右旋转 22 // MouseX只能左右旋转 23 // MouseY只能上下旋转 24 public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 } 25 public RotationAxes axes = RotationAxes.MouseXAndY; 26 27 // 这俩是左右上下旋转时候的灵敏度 28 public float sensitivityX = 15F; 29 public float sensitivityY = 15F; 30 31 // 左右旋转的最大角度 32 public float minimumX = -360F; 33 public float maximumX = 360F; 34 35 //上下旋转最大角度 36 public float minimumY = -60F; 37 public float maximumY = 60F; 38 39 float rotationY = 0F; 40 41 void Update () 42 { 43 //如果是上下左右旋转的模式 44 if (axes == RotationAxes.MouseXAndY) 45 { 46 // 根据鼠标X轴计算摄像机 Y轴旋转角度 47 float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX; 48 49 // 根据鼠标Y轴计算摄像机x轴旋转角度 50 rotationY += Input.GetAxis("Mouse Y") * sensitivityY; 51 52 // 检查上下旋转角度不超过 minimumY和maximumY 53 rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); 54 55 // 设置摄像机旋转角度 56 transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0); 57 } 58 else if (axes == RotationAxes.MouseX)//如果只是左右旋转 59 { 60 transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0); 61 } 62 else//如果只是上下旋转 63 { 64 rotationY += Input.GetAxis("Mouse Y") * sensitivityY; 65 rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); 66 67 transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0); 68 } 69 } 70 71 void Start () 72 { 73 // 冻结刚体的旋转功能 74 // Make the rigid body not change rotation 75 if (GetComponent<Rigidbody>()) 76 GetComponent<Rigidbody>().freezeRotation = true; 77 } 78 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?