- Home /
The question is answered, right answer was accepted
Using euler angles to rotate causes the object to get stuck on the x axis?
Hi everyone,
I wrote a simple script to rotate an object on its axis for the purpose of showing a 3D model. It was as follows:
transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, transform.eulerAngles.z + 0.1f);
Where I would apply the +0.1f to whichever axis I wanted to rotate around.
The script worked fine with the y and z axis, but when applied to the x axis, the model rotated to 90 degrees and then kept jumping between 90 and 89.9. I solved the problem by using transform.rotation instead, but I would like to know why that code didn't work for the future. The object in question is a point cloud rendered using the process from here
Answer by FlaSh-G · Jul 20, 2017 at 07:11 AM
What you encountered is a Gimbal Lock and the exact reason why Unity is using quaternions for rotations and is only offering euler angles for easier access to them.
Right, the solution is to use a quaternion ins$$anonymous$$d:
transform.rotation = Quaternion.Euler(0,0,0.1f) * transform.rotation;
This should do the same. However if the rotation is applied every frame it's better to make it framerate independent
transform.rotation = Quaternion.Euler(0,0,20f * Time.deltaTime) * transform.rotation;
20 degree per second so it takes 18 seconds for a full rotation (20*18 == 360)
Creating a quaternion using Quaternion.Euler can cause Gimbal Locks, too :)
Thank you! I wouldn't have figured that out on my own.