Unity MouseLook 程式碼詳解
阿新 • • 發佈:2018-12-31
最近在做的FPS剛好用到 順帶就解釋了下
using UnityEngine; using System.Collections; // MouseLook rotates the transform based on the mouse delta. // To make an FPS style character: // - Create a capsule. // - Add the MouseLook script to the capsule. // -> Set the mouse look to use MouseX. (You want to only turn character but not tilt it) // - Add FPSInput script to the capsule // -> A CharacterController component will be automatically added. // // - Create a camera. Make the camera a child of the capsule. Position in the head and reset the rotation. // - Add a MouseLook script to the camera. // -> Set the mouse look to use MouseY. (You want the camera to tilt up and down like a head. The character already turns.) [AddComponentMenu("Control Script/Mouse Look")]//設定指令碼路徑 public class MouseLook : MonoBehaviour { public enum RotationAxes { //列舉座標軸 MouseXAndY = 0, MouseX = 1, MouseY = 2 } public RotationAxes axes = RotationAxes.MouseXAndY; //定義X和Y軸 RotationAxes為旋轉軸 public float sensitivityHor = 9.0f;// 水平靈敏度 public float sensitivityVert = 9.0f;// 翻轉靈敏度 public float minimumVert = -45.0f;//設定翻轉角度的最大值和最小值 public float maximumVert = 45.0f; private float _rotationX = 0;//x軸旋轉角度 void Start() { // 使剛體不改變旋轉 Rigidbody body = GetComponent<Rigidbody>(); if (body != null) body.freezeRotation = true;//凍結旋轉 } void Update() { if (axes == RotationAxes.MouseX)//判斷旋轉軸是X or Y軸 { transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityHor, 0);//圍繞X軸旋轉 乘以相應的靈敏度 } else if (axes == RotationAxes.MouseY) { _rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert; _rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);//Mathf.Clamp :限制value的值在min和max之間, //如果value小於min,返回min。 如果value大於max,返回max,否則返回value transform.localEulerAngles = new Vector3(_rotationX, transform.localEulerAngles.y, 0);//localEulerAngles 自身尤拉角, //說這是物件自己相對於父物件的旋轉角度,該變數可用於讀取和設定該角度。不可以用於遞增,角度超過360度將會失效。 } else { float rotationY = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityHor; _rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert; _rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert); transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0); } } }