Rotating an Object 180 degrees

Hello Forum, I have a quick question about rotating. I have several blocks that I’ve scripted to, when clicked on, move towards the camera slightly, rotate 90 degrees around the x-axis, then move back away from the camera. The rotations are, for the most part, correct, but when the rotation reaches 180 degrees, it sets the x rotation value to be really small and flips y and z. Is there anything I can do to have it only rotate x and leave y and z alone? Thanks! :slight_smile:

function Update () 
{
....
xRot = (xRot + 90) % 360;
targetRotation.eulerAngles = Vector3(xRot, 0, 0);
....
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, (Time.time - startTime) / duration);
....
}

function OnMouseDown ()
{
xRot = transform.rotation.eulerAngles.x;
....
}

A characteristic of Euler angles is aliasing; that is, multiple Euler-angle triples can describe the same rotation.

I don’t know how Unity handles orientations internally, but my guess would be that the ‘rotation/localRotation’ fields (which are quaternions) are the base representation for the orientation, and that the Euler angles fields are updated from these as needed. This means that (because of aliasing) you can’t really make any guarantees about what Euler angles you’re going to get back; they’ll always be correct in that they’ll represent the current orientation, but you can’t expect that, say, x will be 180 and that y and z will be 0 or anything like that.

In fact, you can see this in action in the editor. Create an object, and set its x rotation to 180. Then reload the scene, and the Euler angles will have changed to (I think) 0, 180, 180, or something close to it. (The actual values may vary due to numerical imprecision.)

As for the problem you describe, I wouldn’t use Euler angles at all for this. For the specific case of rotating a cube about the x axis in 90-degree increments, I would create and cache four quaternions, one each for identity and rotations of 90, 180, and 270/-90 about the x axis. Keep track of which orientation the cube currently has (i.e. an index from 0 to 3), and when the cube is clicked, advance (cyclically) to the next index. At that point you’ll have both the current rotation and the target rotation, and can interpolate between them as you’re doing currently.

I had a hunch that the way I was doing it wasn’t the best for it, I’ll give your suggestion a go. Thanks for the help! :slight_smile: