Non-oriented Lookat
- tags
- #Optimization #Graphics Programming
- categories
- Shorts
- published
- reading time
- 2 minutes
Useful when we want to have an object pointing in the direction of a vector, but we don’t care about orientation.
It’s important to note that this is not just a potential optimization. Not having an up vector means that we don’t have to worry about degenerate cases where up and dir are aligned.
The classic use case (and the reason I put this together) is to compute the world matrix of debug rays and gizmo arms. Using lookAt to draw force applications and basis vectors is annoying and error-prone, all to draw entities that don’t have an orientation anyway.
glm::mat4 rotate_towards(glm::vec3 dir) {
dir = glm::normalize(dir);
glm::vec3 u = glm::vec3(0, dir.z, dir.y); // basis vector right
glm::vec3 w = glm::cross(dir, u); // basis vector up
glm::mat4 mtx = glm::mat4(0.0f);
mtx[0] = glm::vec4(u, 0.0f);
mtx[1] = glm::vec4(w, 0.0f);
mtx[2] = glm::vec4(dir, 0.0f); // dir is, by definition,
// our forward vector
mtx[3][3] = 1.0f;
return mtx;
}
// bake in translation
glm::mat4 rotate_towards(glm::vec3 pos, glm::vec3 dir) {
dir = glm::normalize(dir);
glm::vec3 u = glm::vec3(0, dir.z, dir.y);
glm::vec3 w = glm::cross(dir, u);
glm::mat4 mtx = glm::mat4(0.0f);
mtx[0] = glm::vec4(u, 0.0f);
mtx[1] = glm::vec4(w, 0.0f);
mtx[2] = glm::vec4(dir, 0.0f);
mtx[3] = glm::vec4(pos, 1.0f);
return mtx;
}
// bake in scale
glm::mat4 rotate_towards(glm::vec3 pos, glm::vec3 dir, float length) {
dir = dir = glm::normalize(dir) * length;
glm::vec3 u = glm::vec3(0, dir.z, dir.y);
glm::vec3 w = glm::cross(dir, u);
glm::mat4 mtx = glm::mat4(0.0f);
mtx[0] = glm::vec4(u, 0.0f);
mtx[1] = glm::vec4(w, 0.0f);
mtx[2] = glm::vec4(dir, 0.0f);
mtx[3] = glm::vec4(pos, 1.0f);
return mtx;
}