Quaternion.EulerAngles rotation bug

I have an object that rotates when “Q” pr “E” pressed, i use that object to rotate camera around player

if (rotationQueued == false && camRotDirection != 0)
        {
            camRotAmount = new Vector3(0, 90 * camRotDirection, 0);
            lastCamRotation = cam.rotation;
            rotationQueued = true;
            targetCameraAngle = lastCamRotation.eulerAngles + camRotAmount;
        }

        cam.eulerAngles = Vector3.Slerp(cam.eulerAngles, targetCameraAngle, 10f * Time.deltaTime);

        if (cam.eulerAngles == targetCameraAngle)
            rotationQueued = false;

it works totally fine when targetCameraAngle is 0, 90 or 180, but when it becomes 270 (or -90) degrees rotated object starts to spin uncontrollably

on GIF ('m pressing “E” to rotate object/camera by -90 degree ox axis Y

Why is that happens and how can i fix this?
Thanks

7422989--908468--5jsc4f.gif

This basically a limitation of eulers, it even mentions in the docs that assigning and reading from euler angles won’t end well. You’ll get things like Gimbal lock and so on.

To fix, you should learn to work with quaternions, or just work with the individual components of pitch, yaw, roll (xyz).
Storing these and doing math on these separate floats is fine, and you can then assign at the end of each frame with:

transform.rotation = Quaternion.Euler(x,y, z);

Or Quaternion.Slerp(currentRotation, Quaternion.Euler(x,y, z)… and so on.

This will avoid the problem because you’re not working with eulers on eulers, but just floats which get converted to a quaternion in a one-way direction.

Thanks alot!
transform.rotation = Quaternion.Euler… works fine