View Full Version : Is my lookAt function right?

12-10-2015, 03:58 PM
The title says it all I just need some feedback if my lookAt function is correct.

mat4 mat4::view(vec3 cameraVector, vec3 targetPos, vec3 rightVector, vec3 upVector)
mat4 result;
mat4 secondMatrix(1.0f);
mat4 firstMat(1.0f);
vec3 directionVector = vec3::normalize(cameraVector - targetPos);

firstMat.elements[0] = rightVector.x;
firstMat.elements[1] = rightVector.y;
firstMat.elements[2] = rightVector.z;
firstMat.elements[4] = upVector.x;
firstMat.elements[5] = upVector.y;
firstMat.elements[6] = upVector.z;
firstMat.elements[8] = directionVector.x;
firstMat.elements[9] = directionVector.y;
firstMat.elements[10] = directionVector.z;

secondMatrix.elements[3] = -cameraVector.x;
secondMatrix.elements[7] = -cameraVector.y;
secondMatrix.elements[11] = -cameraVector.z;

result = firstMat * secondMatrix;

return result;

12-10-2015, 05:16 PM

A lookAt function would be expected to generate an orthogonal matrix, so the three vectors should be perpendicular.

Typically, you would set Z to directionVector but calculate X and Y as X=normalize(cross(upVector, Z)), Y=cross(Z, X). There's no need for rightVector.

Also, you're storing the axes as columns, when they should be rows.

See the gluLookAt reference page (https://www.opengl.org/sdk/docs/man2/xhtml/gluLookAt.xml) for more information.