c++ - 如何使用 glm::lookAt() 旋转对象?

标签 c++ opengl matrix glm-math

我正在研究一个涉及一些圆锥网格的场景,这些圆锥网格将用作延迟渲染器中的聚光灯。我需要缩放、旋转和平移这些圆锥网格,以便它们指向正确的方向。根据我的一位讲师的说法,我可以旋转锥体以与方向 vector 对齐,并通过将其模型矩阵与其返回的矩阵相乘来将它们移动到正确的位置,

glm::inverse(glm::lookAt(spot_light_direction, Spot_light_position, up));

但这似乎不起作用,这样做会导致所有锥体都放置在世界原点上。如果我然后使用另一个矩阵手动平移锥体,似乎锥体甚至没有面向正确的方向。

是否有更好的方法来旋转对象,使其面向特定方向?

这是我当前为每个锥体执行的代码,

//Move the cone to the correct place
glm::mat4 model = glm::mat4(1, 0, 0, 0,
                            0, 1, 0, 0,
                            0, 0, 1, 0,
                            spot_light_position.x, spot_light_position.y, spot_light_position.z, 1);

// Calculate rotation matrix
model *= glm::inverse(glm::lookAt(spot_light_direction, spot_light_position, up));

float missing_angle = 180 - (spot_light_angle / 2 + 90);

float scale = (spot_light_range * sin(missing_angle)) / sin(spot_light_angle / 2);

// Scale the cone to the correct dimensions
model *= glm::mat4(scale, 0,     0,                 0,
                   0,     scale, 0,                 0,
                   0,     0,     spot_light_range,  0,
                   0,     0,     0,                 1);

// The origin of the cones is at the flat end, offset their position so that they rotate around the point.
model *= glm::mat4(1, 0, 0, 0,
                   0, 1, 0, 0,
                   0, 0, 1, 0,
                   0, 0, -1, 1);

我在评论中注意到了这一点,但我会再次提到锥体原点位于锥体平端的中心,我不知道这是否有区别,我只是想我' d 提出来。

最佳答案

您的矩阵顺序似乎是正确的,但 LookAt 函数需要:

glm::mat4 lookAt ( glm::vec3 eye, glm::vec3 center, glm::vec3 up )

这里的眼睛是相机的位置,中心是你正在看的物体的位置(在你的情况下,如果你没有那个位置,你可以使用 聚光灯方向 + 聚光灯位置 )。

所以只要改变

glm::lookAt(spot_light_direction, spot_light_position, up)

glm::lookAt(spot_light_position, spot_light_direction + spot_light_position, up)

关于c++ - 如何使用 glm::lookAt() 旋转对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41104820/

相关文章:

Java vector : how to quickly "symmetrify" a large chunk of a huge sparse matrix

c++ - 以编程方式忽略 printf

C++ : can I do some processing before calling another constructor?

opengl - 什么是基于图 block 的延迟渲染,它的优势是什么?

c++ - 如何使用 openGL 在窗口的左上角创建菜单

arrays - 在 Mac 上将变化的数组从顶点传递到几何着色器

c++ - 套接字编程主机

c++ - 如何在 C++ 标准库中启用散列?

swift - 这个矩阵相邻单元格计数的解决方案有什么问题? ( swift )

c# - 我如何从 C# 打印点阵字体的文本?