Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GLM Make Rotation Matrix from vec3

I am making a game and I need the projectile to face which direction its going. I know which direction its going and I need to make a transformation matrix that would allow me to align the projectile model direction (1, 0, 0) or the positive X axis, to any arbitrary vector. How could I do this in glm?

like image 295
Jerfov2 Avatar asked Dec 19 '15 02:12

Jerfov2


2 Answers

What are you using to represent the direction exactly?

You could do something like this:

glm::mat4 transform = glm::eulerAngleYXZ(euler.y, euler.x, euler.z);

Or via quaternions:

glm::quat rot = glm::angleAxis(glm::radians(angle_in_degrees), glm::vec3(x, y, z));
glm::mat4 rotMatrix = glm::mat4_cast(rot);

Unless you were looking for something as simple as glm::lookAt ?

detail::tmat4x4<T> glm::gtc::matrix_transform::lookAt   
(   
    detail::tvec3< T > const &  eye,     // from
    detail::tvec3< T > const &  center,  // to
    detail::tvec3< T > const &  up       // up
)
like image 80
Mr_Pouet Avatar answered Oct 27 '22 15:10

Mr_Pouet


Hey I figured the answer out, which was close to @Mr_Pouet but here it is:

const glm::vec3 a = ...;
const glm::vec3 b = ...; // in my case (1, 0, 0)
glm::vec3 v = glm::cross(b, a);
float angle = acos(glm::dot(b, a) / (glm::length(b) * glm::length(a)));
glm::mat4 rotmat = glm::rotate(angle, v);

You can replace a or b with anything you want, where a is the vector you want to translate to and b is where you are. We can optimize this if b is (1, 0, 0) or the x-axis, like in my case:

glm::vec3 v = glm::vec3(0, -a.z, a.y);
float angle = acos(a.x / glm::length(a));
glm::mat4 rotmat = glm::rotate(angle, v);

I hope this helps someone!

like image 36
Jerfov2 Avatar answered Oct 27 '22 17:10

Jerfov2