简体   繁体   English

GLM从vec3制作旋转矩阵

[英]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. 我知道它的方向,我需要制作一个转换矩阵,允许我将射弹模型方向(1,0,0)或正X轴与任意向量对齐。 How could I do this in glm? 我怎么能用glm做到这一点?

Hey I figured the answer out, which was close to @Mr_Pouet but here it is: 嘿,我想出了答案,这是接近@Mr_Pouet,但这里是:

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. 您可以将a或b替换为您想要的任何内容,其中a是要转换为的向量,b是您所在的位置。 We can optimize this if b is (1, 0, 0) or the x-axis, like in my case: 如果b是(1,0,0)或x轴,我们可以优化它,就像我的情况一样:

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! 我希望这可以帮助别人!

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 ? 除非你在寻找像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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM