unity3d 第一人称脚本解释MouseLook

时间:2023-03-09 16:34:54
unity3d 第一人称脚本解释MouseLook
 using UnityEngine;
using System.Collections; /// MouseLook rotates the transform based on the mouse delta.
/// Minimum and Maximum values can be used to constrain the possible rotation /// To make an FPS style character:
/// - Create a capsule.
/// - Add the MouseLook script to the capsule.
/// -> Set the mouse look to use LookX. (You want to only turn character but not tilt it)
/// - Add FPSInputController script to the capsule
/// -> A CharacterMotor and a CharacterController component will be automatically added. /// - Create a camera. Make the camera a child of the capsule. Reset it's transform.
/// - Add a MouseLook script to the camera.
/// -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.)
[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour {
//3个枚举
// 这个表示当前控制模式,分别是
// MouseXAndY上下左右旋转
// MouseX只能左右旋转
// MouseY只能上下旋转
public enum RotationAxes { MouseXAndY = , MouseX = , MouseY = }
public RotationAxes axes = RotationAxes.MouseXAndY; // 这俩是左右上下旋转时候的灵敏度
public float sensitivityX = 15F;
public float sensitivityY = 15F; // 左右旋转的最大角度
public float minimumX = -360F;
public float maximumX = 360F; //上下旋转最大角度
public float minimumY = -60F;
public float maximumY = 60F; float rotationY = 0F; void Update ()
{
//如果是上下左右旋转的模式
if (axes == RotationAxes.MouseXAndY)
{
// 根据鼠标X轴计算摄像机 Y轴旋转角度
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX; // 根据鼠标Y轴计算摄像机x轴旋转角度
rotationY += Input.GetAxis("Mouse Y") * sensitivityY; // 检查上下旋转角度不超过 minimumY和maximumY
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); // 设置摄像机旋转角度
transform.localEulerAngles = new Vector3(-rotationY, rotationX, );
}
else if (axes == RotationAxes.MouseX)//如果只是左右旋转
{
transform.Rotate(, Input.GetAxis("Mouse X") * sensitivityX, );
}
else//如果只是上下旋转
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, );
}
} void Start ()
{
// 冻结刚体的旋转功能
// Make the rigid body not change rotation
if (GetComponent<Rigidbody>())
GetComponent<Rigidbody>().freezeRotation = true;
}
}