我正在使用 glfw、glad 和 glm 修补 OpenGL。在我使用的其中一个教程中,他们演示了 glm 的一些简单用法:
glm::vec4 vec(1.0f, 0.0f, 0.0f, 1.0f);
glm::mat4 trans;
trans = glm::translate(trans, glm::vec3(1.0f, 1.0f, 0.0f));
vec = trans * vec;
std::cout << vec.x << vec.y << vec.z << std::endl;
当我编译并运行这段代码时,我得到了垃圾值(通常是 NAN)。教程特别指出实例化
glm::mat4 trans;
默认情况下会为变量“trans”创建一个单位矩阵。我在想也许这就是问题所在,尽管我已经证实 glm 默认情况下确实这样做。
如果有帮助,您可以找到整个源文件 here在第 308 行。非常感谢您的宝贵时间!
最佳答案
您必须初始化矩阵变量 glm::mat4 trans
。
glm API documentation指The OpenGL Shading Language specification 4.20 .
5.4.2 Vector and Matrix Constructors
If there is a single scalar parameter to a vector constructor, it is used to initialize all components of the constructed vector to that scalar’s value. If there is a single scalar parameter to a matrix constructor, it is used to initialize all the components on the matrix’s diagonal, with the remaining components initialized to 0.0.
这意味着,单位矩阵可以通过单个参数 1.0 进行初始化:glm::mat4(1.0f)
。
像这样改变你的代码:
glm::mat4 trans(1.0f);
另见 OpenGL Mathematics (GLM); 2. Vector and Matrix Constructors
关于c++ - glm 在简单翻译中返回 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49058381/