Rotating Quaternion results in unexpected behaviour

So I’m trying to make a little side scrolling platformer, but using a 3D environment rather than a 2D one. Right now I’m trying to add a function which would allow my player to increase and decrease the look angle of a gun they’re holding. When I run the game and I edit the X value of the rotation in the inspector it behaves like I expect, but when the code edits it, the gun suddenly points towards the player. Further trying to rotate causes the Y and Z to keep flipping wildly until they finally reach 90 and 180 respectively then just stop changing.

On the side of the player game object is an empty object I use as the gun spawn location. I’m editing the weapon spawn to try and rotate the gun.

Any help about what I’m missing is appreciated.

Thank you,

void RotateGun()
    {
        float rAxis = Input.GetAxis("Vertical");
        Quaternion currentRot = WeaponSpawn.transform.rotation;


        if ( rAxis != 0 && shouldRotate == true )
        {
            shouldRotate = false;

            if ( rAxis > 0 )
            {
                currentRot.x = currentRot.x - 10;
                WeaponSpawn.transform.rotation = currentRot;
            }
            else if ( rAxis < 0 )
            {
                currentRot.x = currentRot.x + 10;
                WeaponSpawn.transform.rotation = currentRot;
            }
        }

        if ( rAxis == 0 )
        {
            shouldRotate = true;
        }
    }

Quaternions are not like vectors and require more complex math. To easily create quaternions use Quaternion.Euler.

1 Like