Search Unity

Quaternion.LookRotation() What does it do?

Discussion in 'Scripting' started by David Bennell, Aug 2, 2010.

  1. David Bennell

    David Bennell

    Joined:
    Apr 25, 2010
    Posts:
    5
    Hi I have an embarrassingly simple problem that I just can't solve.

    I am using Unity3D as a client and I have a server that uses an External 3D Math Library that includes Quaternions but does not included the method "Quaternion.LookRotation()" or anything that I can find like it.

    So what does Quaternion.LookRotation() do exactly?
    The best I could come up with after searching around the interwebs was...

    Vector3 dir = (Target.position - transform.position);
    Vector3 axis = Vector3.Cross(Vector3.up, dir.normalized);
    float angle = Vector3.Dot(Vector3.right, dir.normalized);

    rotationToTarget = Quaternion.AngleAxis(angle, axis);
    //rotationToTarget = Quaternion.LookRotation(dir);

    //transform.rotation *= rotationToTarget
    transform.rotation = Quaternion.Slerp(transform.rotation, rotationToTarget, Time.deltaTime);

    But this just rotates to 'identity'?
    I am missing something obvious and simple I know I am...

    Not 'strictly' a Unity3D question exactly I know, but currently I have spent 3 days trying to work this out and it seems like it should be so simple.
     
  2. Jesse Anders

    Jesse Anders

    Joined:
    Apr 5, 2008
    Posts:
    2,857
    I'm not sure what the code you posted is supposed to do, but it doesn't make any sense to me (and I think it's safe to say it's not what LookRotation() does).

    LookRotation() basically does the same thing as a typical 'look-at' view transform function, except that there's no translation involved (since we're just dealing with a quaternion), and the transform is not inverted.

    The code might look something like this (untested):

    Code (csharp):
    1. vector3 z = direction.normalize();
    2. vector3 x = cross(up, z).normalize();
    3. vector3 y = cross(z, x);
    4. return quaternion_from_basis_vectors(x, y, z);
    The 'quaternion from basis vectors' part is basically a matrix-to-quaternion conversion, which is a little less straightforward than converting the other way, but is nevertheless fairly well documented online and elsewhere.