- Home /
Calculate Quaternion.LookRotation manually
Hi,
After many hours of research and getting in nowhere, I was wonder if anybody here knows how on earth Unity does the Quaternion.LookRotation calculation.
Im asking this because I
m working on a school project which I have to create my stuff from scratch (Quaternion class,Vector class etc). So the look operation is the only thing I didn’t managed to work.
I would like to see both ways, meaning the "without the up vector" and "with up vector" if there is any other differences besides the automatic use of Vector3.up in the first one.
Thanks for your time.
Not an exact duplicate, but there is some source in this answer:
http://answers.unity3d.com/questions/467614/what-is-the-source-code-of-quaternionlookrotation.html
I did see this question before and in fact, it was the one which made me believe that a look rotation would be executed from a quaternion calculation. Before that, I did not even know from where to start. Thanks!
Answer by robertbu · Oct 29, 2014 at 03:49 AM
If I had to write Quaternion.LookRotation(), I might do something like this:
function MyLookRotation(dir : Vector3, up : Vector3) : Quaternion {
if (dir == Vector3.zero) {
Debug.Log("Zero direction in MyLookRotation");
return Quaternion.identity;
}
if (up != dir) {
up.Normalize();
var v = dir + up * -Vector3.Dot(up, dir);
var q = Quaternion.FromToRotation(Vector3.forward, v);
return Quaternion.FromToRotation(v, dir) * q;
}
else {
return Quaternion.FromToRotation(Vector3.forward, dir);
}
}
Note this is built on Quaternion.FromToRotation(), which you would then have to unravel if you need everything from scratch.
$$anonymous$$y goodness I spent so much time trying to find the solution you wrote! I cannot even imagine how you could possibly arrive at this. Anyway thanks alooooot for your answer.
If you have the time, could you explain why you did multiply the dir+up with the negative dot(up,dir) ?
If a millionaire read his answers, please! Buy him a Ferrari. Don't forget to give him an up vote
I don't know if this is an exact match to Quaternion.LookRotation(), but in a bit of testing, it behaves in a similar fashion. What this code does is use the 'up' vector as a normal on a plane. The 'dir + up..' part take the direction and projects it on the plane defined by the 'up' vector. The result is that the first FromToRotation() (line 10) uses the 'up' vector as an axis of rotation. After that rotation is done...after the rotation has aligned things as much as it can using 'up' as the axis...it rotates from that direction to the final direction in a second rotation. Note that if 'dir == up' then you cannot use it as an axis.
This is the best solution I have ever found! I'm making my own engine and was trying to replicate the famous LookRotation function. This algorithm works like a charm! I used this code for FromToRotation function.