Rotating using Quaternion

Hi there.

I have a simple question for you. I have read in some topics in this forum that Quaternion can be used to rotate a vector. So, I did this

transform.eulerAngles = Quaternion.AngleAxis(90,Vector3.up)* new Vector3(0,0,1);

My idea was to rotate the vector 90 degrees in Z Axis but it did not work.

So, I changed the code by this

transform.rotation = Quaternion.LookRotation(Quaternion.AngleAxis(180,Vector3.up)* new Vector3(0,0,1));

and it worked. The question is, why the fist code did not work?

Thanks

To be honest, I have no idea how either of those would compile. In both cases you are multiplying a Quaternion and a Vector3, which I didn’t think was possible.

It is possible, the only requirement is the order:

This is allowed:

Vector = Quaternion*Vector

This is not allowed:

Vector = Vector*Quaternion

What I am doing right now is trying to understand how it woks

This is a reference: Unity - Scripting API: Quaternion.operator *

Learner

This code:

transform.eulerAngles = Quaternion.AngleAxis(90,Vector3.up)* new Vector3(0,0,1);

First rotates the vector (0, 0, 1) 90 degrees about the y axis to yield (1, 0, 0). You then interpret this as a set of Euler angles, with the result being a rotation of 1 degree about the x axis, which I doubt is what you want. In short, this operation is very unlikely to produce meaningful results.

This code:

transform.rotation = Quaternion.LookRotation(
    Quaternion.AngleAxis(180, Vector3.up) * new Vector3(0,0,1));

Rotates the vector (0, 0, 1) to yield (0, 0, -1), and then builds a rotation that looks in that direction. If your intent was to point the object along the -z axis, then the above code is technically correct. That said, you could simply write:

transform.rotation = Quaternion.LookRotation(-Vector3.forward);

And get the same effect.

Thanks Jesse, this is the kind of answer I was looking for. The reason I did that was just to understand Quaternion. Could you please tell me why X axis is affected in the first scenario.

Edit: I got it!!!

Thanks for taking time to answer

Regards

Learner

The field ‘eulerAngles’ represents the object’s orientation in Euler-angle form. Euler angles represent a sequence of transforms about a series of axes. Unity uses the order Z->X->Y, I believe, which means that the ‘z’ rotation is applied first (about the cardinal z axis), followed by the x and y rotations, respectively.

The vector (1, 0, 0), when interpreted as a set of Euler angles (using degrees, as Unity does), therefore specifies a rotation of 1 degree about the x axis. (Since the y and z elements are 0, there is no rotation about the y or z axes, and the rotation reduces to a simple axis-angle rotation with the cardinal x axis as the axis, and 1 degree as the angle.)

Thanks Jesse, very clear answer. I will continue studying Quaternion!!!

Regards

Learner