FPS第一人称相机360度无死角旋转,ESC按键可以控制光标显示隐藏。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SmoothMouseLook : MonoBehaviour {
public float sensitivity = 4.0f;
[HideInInspector]
public float sensitivityAmt = 4.0f;
private float minimumX = -360f;
private float maximumX = 360f;
private float minimumY = -85f;
private float maximumY = 85f;
[HideInInspector]
public float rotationX = 0.0f;
[HideInInspector]
public float rotationY = 0.0f;
[HideInInspector]
public float inputY = 0.0f;
public float smoothSpeed = 0.35f;
private Quaternion originalRotation;
private Transform myTransform;
[HideInInspector]
public float recoilX;
[HideInInspector]
public float recoilY;
void Start(){
if (rigidbody){rigidbody.freezeRotation = true;}
myTransform = transform;
originalRotation = myTransform.localRotation;
Vector3 tempRotation = new Vector3(0,Camera.main.transform.eulerAngles.y,0);
originalRotation.eulerAngles = tempRotation;
sensitivityAmt = sensitivity;
UnityEngine.Cursor.Visble = false;
}
void Update(){
if(Time.timeScale > 0 && Time.deltaTime > 0){
Screen.lockCursor = true;
UnityEngine.Cursor.Visble = false;
rotationX += Input.GetAxisRaw("Mouse X") * sensitivityAmt * Time.timeScale;
rotationY += Input.GetAxisRaw("Mouse Y") * sensitivityAmt * Time.timeScale;
if(maximumY - Input.GetAxisRaw("Mouse Y") * sensitivityAmt * Time.timeScale < recoilY){
rotationY += recoilY;
recoilY = 0.0f;
}
if(maximumX - Input.GetAxisRaw("Mouse X") * sensitivityAmt * Time.timeScale < recoilX){
rotationX += recoilX;
recoilX = 0.0f;
}
rotationX = ClampAngle (rotationX, minimumX, maximumX);
rotationY = ClampAngle (rotationY, minimumY - recoilY, maximumY - recoilY);
inputY = rotationY + recoilY;
Quaternion xQuaternion = Quaternion.AngleAxis (rotationX + recoilX, Vector3.up);
Quaternion yQuaternion = Quaternion.AngleAxis (rotationY + recoilY, -Vector3.right);
myTransform.rotation = Quaternion.Slerp(myTransform.rotation , originalRotation * xQuaternion * yQuaternion, smoothSpeed * Time.smoothDeltaTime * 60 / Time.timeScale);
myTransform.rotation = Quaternion.Euler(myTransform.rotation.eulerAngles.x, myTransform.rotation.eulerAngles.y, 0.0f);
}else{
Screen.lockCursor = false;
UnityEngine.Cursor.Visble = true;
}
}
public static float ClampAngle (float angle, float min, float max){
angle = angle % 360;
if((angle >= -360F) && (angle <= 360F)){
if(angle < -360F){
angle += 360F;
}
if(angle > 360F){
angle -= 360F;
}
}
return Mathf.Clamp (angle, min, max);
}
}