Search code examples
c#unity-game-enginequaternions

how to chagne transform.eulerAngles to quaternion


i made camera rotating to observe an object

it is rotating part mouse left button

 if (Input.GetMouseButton(0))
    {
            xMovement = Input.GetAxis("Mouse X");
            yMovement = Input.GetAxis("Mouse Y");
         
        
             //1
            //Quaternion qurEuler = Quaternion.Euler
            //    (new Vector3(-yRotation, xRotation, 0));
            //Quaternion quaternion = transform.rotation;
            //
            //2
            //transform.rotation = (quaternion * qurEuler);
            //3
            //  transform.rotation *= Quaternion.AngleAxis(1, new Vector3(-yRotation, xRotation, 0));
            //4
            //transform.Rotate(-yRotation, xRotation, 0);

            //i use this 
            transform.eulerAngles += new Vector3(-yRotation, xRotation, 0);
        }

but this way have gimbal lock. 1 , 2 , 3 ,4 way is not comfortable

After I rotate the object it was impossible to try to restore the object to its original rotation. transform.eulerAngles += new Vector3(-yRotation, xRotation, 0) is possible to restore rotation I want to know what quarternion is using the same method as transform.eulerAngles


Solution

  • If you wanted to use quaternions to do the same thing as your transform.eulerAngles += new Vector3(-yRotation, xRotation, 0); method, you would have to apply the Y axis rotation in global axes, and then the X axis rotation in local axis:

    if (Input.GetMouseButton(0))
    {
        xMovement = Input.GetAxis("Mouse X");
        yMovement = Input.GetAxis("Mouse Y");
      
        Quaternion yRot = Quaternion.Euler(0f, xMovement, 0f);
        Quaternion xRot = Quaternion.Euler(-yMovement, 0f, 0f);
    
        transform.rotation = yRot * transform.rotation * xRot;
        // ...
    

    See this question for more information on how to use quaternion multiplication.