Skip to content

Instantly share code, notes, and snippets.

@gszauer
Created May 30, 2019 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gszauer/d76f74fdaa7fab7339271ba785ffa28d to your computer and use it in GitHub Desktop.
Save gszauer/d76f74fdaa7fab7339271ba785ffa28d to your computer and use it in GitHub Desktop.
OpenGL Look At
mat4 lookAt(const vec3& position, const vec3& target, const vec3& up) {
// Remember, forward is negative z
vec3 f = normalized(target - position) * -1.0f;
vec3 r = cross(up, f);
if (r == vec3(0, 0, 0)) {
std::cout << "WARNING: mat4 lookAt has invalid right vector\n";
return mat4(); // Error
}
normalize(r);
vec3 u = normalized(cross(f, r));
vec3 t = vec3(
-dot(r, position),
-dot(u, position),
-dot(f, position)
);
return mat4(
// Transpose upper 3x3 matrix to invert it
r.x, u.x, f.x, 0,
r.y, u.y, f.y, 0,
r.z, u.z, f.z, 0,
t.x, t.y, t.z, 1
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment