Quaternion problem

Hello everyone. I am struggling with a problem which I cannot fix because I don’t understand all about Quaternion. It’s for me a little bit confusing. I did a script so as to move an object using 3 axis XYZ. I added a function so as to balance Z axis rotation to nearest 90 degrees. All works as expected when I move on axe XYZ, but there is a strange behavior instead previous balancing when I modify rotation X and Y. It balances on Z axis as usual, but effect is no good. It seems to me that I should balance now Y axis instead Z. I guess that there is a logical explanation. Have you an idea ? Thank you ++

Vector3 selectedAxis = new Vector3(0, 0, 1); // balance Z axis

    Vector3 RotateAxisToNearestSide(Vector3 eulerAngles, Vector3 selectedAxis)
    {
        Vector3 rounded = RoundToNearest90Degree(eulerAngles);
        Vector3 slerped = Vector3.Slerp(eulerAngles, rounded, Time.deltaTime * 2f);

        return SetSelectedAxis(eulerAngles, slerped, selectedAxis);
    }

    Vector3 RoundToNearest90Degree(Vector3 eulerAngles)
    {
        for (int i = 0; i < 3; i++)
            eulerAngles[i] = Mathf.Round(eulerAngles[i] / 90f) * 90f;

        return eulerAngles;
    }

    Vector3 SetSelectedAxis(Vector3 original, Vector3 desired, Vector3 selectedAxis)
    {
        for (int i = 0; i < 3; i++)
            if (selectedAxis[i] != 0)
                selectedAxis[i] = desired[i];
            else
                selectedAxis[i] = original[i];

        return selectedAxis;
    }

void FixedUpdate()
    {
       this.transform.localEulerAngles = RotateAxisToNearestSide(this.transform.localEulerAngles, selectedAxis);
    }

Is there maybe a relation with the Gimbal Lock ?

The xyz components of quaternions do not represent an axis like you might think. It’s not an angle-axis representation where the direction corresponds to a direction in 3D space. It’s a 4D complex number, not an axis with a rotation angle around said axis.

1 Like

Hum. You are right. As I said I have to go deeper with Quaternion and Vector3. It’s a little bit confusing for me. Thank you for your explanation ++

Ok. I found my mistake. I have to use transform.forward and not Vector3.forward. It works ++