Constructing the lookat() matrix directly

While it is possible to construct the lookat() matrix from a series of rotation and translation transforms, it is simpler to construct the matrix directly from the relevant vectors. Given an eye point e, a lookat point l, and an up vector U, let F be the vector from e to l:

Normalize as follows:

Let s = f X u' and u = s X f ('X' is cross-product). Construct the matrix M as follows:

Finally, construct the translation matrix T that translates e to the origin:

The final lookat matrix L that transforms points in world coordinates to points in viewing coordinates, with the eye at the origin, the lookat point l down the -Z axis, and the up vector U in the YZ plane, is given by:

Note that the extra cross-product to find u from u' allows us a bit more flexibility: the specified up vector U need not be perfectly perpendicular to the viewing direction, but merely in the desired vertical plane.