Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

Mouse Look (Script)

Discussion in 'Scripting' started by Bowwers, Mar 13, 2014.

Thread Status:
Not open for further replies.
  1. Bowwers

    Bowwers

    Joined:
    Jan 8, 2014
    Posts:
    3
    First of all I would like to apologise if this thread has been made already. However I have been looking for a good 1.5-2 hours now with no luck.

    Basically I have done my research and discovered that the Mouse Look (Script) in Unity is bugged in the fact that the development team haven't implemented the "X" axis into the script. I have opened it up and knowing nothing about scripting I can see myself where the error is. However, all fixes I find on the internet tell you to change code or copy and paste this in the right place and like I say, I haven't got a clue when it comes to scripting so no idea which bits need changing.

    I have tried changing parts of the code myself with no luck.

    I was hoping someone could go into the code and change the relevant bit for me and copy and paste the whole code here so basically I can just copy and paste the whole code into Unity.

    I will be very grateful if someone who knows what they are doing could do this for me. It will only be a 5 minute job.

    Many Thanks

    Dean Hillary

    [Current Code] - I have highlighted the bit I believe to be bugged in red

    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 {

    public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
    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)
    {
    float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;

    rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
    rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

    transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);

    }
    else if (axes == RotationAxes.MouseX)
    {
    transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
    }
    else
    {
    rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
    rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

    transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
    }
    }

    void Start ()
    {
    // Make the rigid body not change rotation
    if (rigidbody)
    rigidbody.freezeRotation = true;
    }
    }
     
    JannPorzig likes this.
  2. ladyonthemoon

    ladyonthemoon

    Joined:
    Jun 29, 2015
    Posts:
    236
    How is it that nobody commented this thread?

    Updated version:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [AddComponentMenu("Camera-Control/Mouse Look")]
    5. public class MouseLook : MonoBehaviour
    6. {
    7.  
    8.     public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
    9.     public RotationAxes axes = RotationAxes.MouseXAndY;
    10.     public float sensitivityX = 15F;
    11.     public float sensitivityY = 15F;
    12.  
    13.     public float minimumX = -360F;
    14.     public float maximumX = 360F;
    15.  
    16.     public float minimumY = -60F;
    17.     public float maximumY = 60F;
    18.  
    19.     private Rigidbody rb;
    20.     float rotationY = 0F;
    21.  
    22.     void Start ()
    23.     {
    24.         rb = GetComponent<Rigidbody> ();
    25.  
    26.         // Make the rigid body not change rotation
    27.         if (GetComponent<Rigidbody>())
    28.             rb.freezeRotation = true;
    29.     }
    30.  
    31.     void Update ()
    32.     {
    33.         if (axes == RotationAxes.MouseXAndY)
    34.         {
    35.             float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;
    36.  
    37.             rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
    38.             rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
    39.  
    40.             transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
    41.         }
    42.         else if (axes == RotationAxes.MouseX)
    43.         {
    44.             transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
    45.         }
    46.         else
    47.         {
    48.             rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
    49.             rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
    50.  
    51.             transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
    52.         }
    53.     }
    54. }

    It works rather well when attached directly to the player; except that the mouse pointer is still visible on the screen and that "Mouse x" and "Mouse y" are independent from each other.

    It doesn't work well at all when attached to a camera child of the player.

    I would be grateful is someone was willing to help in the matter, thanks! :)
     
    Deleted User likes this.
  3. jimroberts

    jimroberts

    Joined:
    Sep 4, 2014
    Posts:
    560
    See:
    Here is a simplified version of a FPS mouse look script that will prevent rotation when looking 90 degrees up or down.
    Code (CSharp):
    1. private float X;
    2. private float Y;
    3.  
    4. public float Sensitivity;
    5.  
    6. void Awake()
    7. {
    8.     Vector3 euler = transform.rotation.eulerAngles;
    9.     X = euler.x;
    10.     Y = euler.y;
    11. }
    12.  
    13. void Update()
    14. {
    15.     const float MIN_X = 0.0f;
    16.     const float MAX_X = 360.0f;
    17.     const float MIN_Y = -90.0f;
    18.     const float MAX_Y = 90.0f;
    19.  
    20.     X += Input.GetAxis("Mouse X") * (Sensitivity * Time.deltaTime);
    21.     if (X < MIN_X) X += MAX_X;
    22.     else if (X > MAX_X) X -= MAX_X;
    23.     Y -= Input.GetAxis("Mouse Y") * (Sensitivity * Time.deltaTime);
    24.     if (Y < MIN_Y) Y = MIN_Y;
    25.     else if (Y > MAX_Y) Y = MAX_Y;
    26.  
    27.     transform.rotation = Quaternion.Euler(Y, X, 0.0f);
    28. }
    You can lock the cursor with Cursor.lockState and hide the cursor with Cursor.visible.
     
  4. ladyonthemoon

    ladyonthemoon

    Joined:
    Jun 29, 2015
    Posts:
    236
    Thank you! :)
     
  5. malinin05

    malinin05

    Joined:
    Jun 6, 2020
    Posts:
    1
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class MouseControll : MonoBehaviour {

    private Vector3 Rot;
    private float xRot;
    private float yRot;
    private float xCurrRot;
    private float yCurrRot;
    [SerializeField]
    private Camera fpcCamera;
    [SerializeField]
    private GameObject fpcObject;
    public float mouseSensetive;
    private float xRotVelocity;
    private float yRotVelocity;
    [SerializeField]
    private float smoothDampTime = 0.1f;



    // Use this for initialization
    void Start () {
    mouseSensetive=1f;
    }

    // Update is called once per frame
    void Update () {
    MouseMove();
    }

    private void MouseMove()
    {
    xRot+=Input.GetAxis("Mouse Y")*mouseSensetive;
    yRot+=Input.GetAxis("Mouse X")*mouseSensetive;
    xRot=Mathf.Clamp(xRot,-90,90);

    xCurrRot=Mathf.SmoothDamp(xCurrRot, xRot, ref xRotVelocity, smoothDampTime);
    yCurrRot=Mathf.SmoothDamp(yCurrRot, yRot, ref yRotVelocity, smoothDampTime);

    fpcCamera.transform.rotation=Quaternion.Euler(xCurrRot,yCurrRot,0f);
    fpcObject.transform.rotation=Quaternion.Euler(0f,yCurrRot,0f);

    }
    }
     
    JannPorzig likes this.
  6. Peytoncl

    Peytoncl

    Joined:
    Jun 12, 2020
    Posts:
    2
    why is it inverted
     
    portalpig and JannPorzig like this.
  7. whoisgliese

    whoisgliese

    Joined:
    Jun 4, 2020
    Posts:
    8
    thanks man
     
  8. TutorAddicts

    TutorAddicts

    Joined:
    Feb 17, 2019
    Posts:
    2
    Bad Code Practice
     
  9. freakiestloki71

    freakiestloki71

    Joined:
    Sep 23, 2022
    Posts:
    1
    I am really late to the thread, but if someone could help me that would be great.
    I used the code in this thread for my look script but and it works great except when my character turns 'w', which moved the character forwards, is now moving my character forwards. I used ladyonthemoon's code and this is my movement code.


    using UnityEngine;
    using System.Collections;

    // This script moves the character controller forward
    // and sideways based on the arrow keys.
    // It also jumps when pressing space.
    // Make sure to attach a character controller to the same game object.
    // It is recommended that you make only one call to Move or SimpleMove per frame.

    public class movplayer : MonoBehaviour
    {
    CharacterController characterController;

    public float speed = 6.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;

    private Vector3 moveDirection = Vector3.zero;

    void Start()
    {
    characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
    if (characterController.isGrounded)
    {
    // We are grounded, so recalculate
    // move direction directly from axes

    moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
    moveDirection *= speed;

    if (Input.GetButton("Jump"))
    {
    moveDirection.y = jumpSpeed;
    }
    }

    // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
    // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
    // as an acceleration (ms^-2)
    moveDirection.y -= gravity * Time.deltaTime;

    // Move the controller
    characterController.Move(moveDirection * Time.deltaTime);

    }
    }
     
  10. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,761
    No, you're not late but you are necroing/hijacking an existing thread. Please create your own thread instead.

    Also, please use code-tags when posting code and not plain text.

    Thanks.
     
Thread Status:
Not open for further replies.