What exactly is the UP vector in OpenGL's LookAt function?

Jeremy L picture Jeremy L · May 17, 2012 · Viewed 34.3k times · Source

this is related to The LookAt target location doesn't matter if it is z = 0 or z = 1000 or -1000?

I tried

    gluLookAt(512, 384, 2000,
              512, 384, 0,
              0.0f, 1.0f, 0.0f);

and things work fine, and now I change the 3rd row (the UP vector), last number to 0.8:

    gluLookAt(512, 384, 2000,
              512, 384, 0,
              0.0f, 1.0f, 0.8f);

and it is exactly the same... next I tried and modified the 3rd line, the first number to 0.8:

    gluLookAt(512, 384, 2000,
              512, 384, 0,
              0.8f, 1.0f, 0.8f);

Now the view is like it rotated 45 degree to the left. How does this UP vector work?

Answer

Zack Brown picture Zack Brown · May 17, 2012

The up vector is used to create a cross product between the eye and centre vector supplied to gluLookAt.

From the GLKit headers on iOS, you can see the implementation as:

static __inline__ GLKMatrix4 GLKMatrix4MakeLookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ)
{
    GLKVector3 ev = { eyeX, eyeY, eyeZ };
    GLKVector3 cv = { centerX, centerY, centerZ };
    GLKVector3 uv = { upX, upY, upZ };
    GLKVector3 n = GLKVector3Normalize(GLKVector3Add(ev, GLKVector3Negate(cv)));
    GLKVector3 u = GLKVector3Normalize(GLKVector3CrossProduct(uv, n));
    GLKVector3 v = GLKVector3CrossProduct(n, u);

    GLKMatrix4 m = { u.v[0], v.v[0], n.v[0], 0.0f,
        u.v[1], v.v[1], n.v[1], 0.0f,
        u.v[2], v.v[2], n.v[2], 0.0f,
        GLKVector3DotProduct(GLKVector3Negate(u), ev),
        GLKVector3DotProduct(GLKVector3Negate(v), ev),
        GLKVector3DotProduct(GLKVector3Negate(n), ev),
        1.0f };

    return m;
}

The accepted answer in this question How do I use gluLookAt properly? provides a good description of what the up vector actually impacts.

(The intuition behind the "up" vector in gluLookAt is simple: Look at anything. Now tilt your head 90 degrees. Where you are hasn't changed, the direction you're looking at hasn't changed, but the image in your retina clearly has. What's the difference? Where the top of your head is pointing to. That's the up vector.)