Advertisement
ZeronSix

Smooth Mouse Look

Jul 16th, 2013
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.97 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. /// <summary>
  5. /// One instance will turn the whole player body and one - only camera
  6. /// </summary>
  7. public enum RotationAxes { X, Y, Both };
  8.  
  9. /// <summary>
  10. /// FPS mouse look.
  11. /// </summary>
  12. [AddComponentMenu("FPS Stuff/Smooth Mouse Look")]
  13. public class MouseLook : MonoBehaviour
  14. {
  15.     public RotationAxes rotationAxes;
  16.     public Vector2 mouseSensitivity;
  17.     public Vector2 mouseSmoothness;
  18.     public Vector2 verticalRestriction;
  19.  
  20.     private Vector2 lookDelta = Vector2.zero;
  21.     private Vector2 smooth = Vector2.zero;
  22.     private Vector2 smoothVelocity = Vector2.zero;
  23.  
  24.     void Update()
  25.     {
  26.         Vector2 mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X") * mouseSensitivity.x,
  27.                                          -Input.GetAxisRaw("Mouse Y") * mouseSensitivity.y);
  28.         lookDelta += mouseDelta;
  29.  
  30.         // turn player on Y axis
  31.         if (rotationAxes == RotationAxes.X)
  32.         {
  33.             smooth.x = Mathf.SmoothDamp(smooth.x, lookDelta.x, ref smoothVelocity.x, mouseSmoothness.x);
  34.  
  35.             Quaternion rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, smooth.x, transform.rotation.eulerAngles.z);
  36.             rigidbody.MoveRotation(rotation);
  37.         }
  38.         else if (rotationAxes == RotationAxes.Y)
  39.         {
  40.             smooth.y = Mathf.SmoothDamp(smooth.y, lookDelta.y, ref smoothVelocity.y, mouseSmoothness.y);
  41.             smooth.y = ClampAngle(smooth.y, verticalRestriction.x, verticalRestriction.y);
  42.  
  43.             Quaternion rotation = Quaternion.Euler(smooth.y, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
  44.             transform.rotation = rotation; // camera has no rigidbody so use transform
  45.         }
  46.     }
  47.  
  48.     static float ClampAngle(float angle, float min, float max)
  49.     {
  50.         if (angle < -360)
  51.             angle += 360;
  52.         if (angle > 360)
  53.             angle -= 360;
  54.         return Mathf.Clamp(angle, min, max);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement