Search code examples
unity-game-enginequaternions

What's wrong with this mouse look function?


I've been toying with iterations of this for a few weeks, but it's still busted so I thought id reach out for some help. This performs as expected except for one glaring issue: the output sensitivity appears to be super pitch dependent.

`

        //Grab mouse input
        float rotateHorizontal = Input.GetAxis("Mouse X");
        float rotateVertical = -Input.GetAxis("Mouse Y");

        Vector3 rotation = new Vector3(rotateVertical, rotateHorizontal, 0);

        transform.Rotate(sensitivity * Time.deltaTime * rotation);

        Vector3 eAngles = transform.eulerAngles;
        float pitch = eAngles.x;
        pitch = ClampAngle(pitch, -camClamp, camClamp); 
        transform.localEulerAngles = new Vector3(pitch, eAngles.y, eAngles.z);

`

What am I missing? I'm pretty sure it's not the clamp angle function since I stole it from a reputable source. Thanks for the help.


Solution

  • Rotations are hard! I think it was a rotation order problem. Switched to quaternions, problem remained, then found this lovely thread and reordered the operands.

            originalRotation = transform.localRotation;
        //Grab mouse input
        float rotateHorizontal = Input.GetAxis("Mouse X");
        float rotateVertical = Input.GetAxis("Mouse Y");
    
        Quaternion xQuaternion = Quaternion.AngleAxis(rotateHorizontal, Vector3.up);
        Quaternion yQuaternion = Quaternion.AngleAxis(rotateVertical, -Vector3.right);
    
        transform.localRotation = xQuaternion * originalRotation * yQuaternion;
    
        Vector3 eAngles = transform.eulerAngles;
        float pitch = eAngles.x;
        pitch = ClampAngle(pitch, -camClamp, camClamp); 
        transform.localEulerAngles = new Vector3(pitch, eAngles.y, eAngles.z);
    

    Thank you freya holmer

    Order matters in quaternion multiplication!