unity3d 第一人称脚本解释:MouseLook

 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 }
原文地址:https://www.cnblogs.com/niboy/p/4269612.html