简体   繁体   English

如何在OpenGL中正确旋转和缩放对象?

[英]How to properly rotate and scale an object in OpenGL?

I'm trying to build the model matrix every frame, for that I'm creating a translation, rotation, and scale matrix and multiplying it. 我正在尝试每帧构建模型矩阵,为此我创建了平移,旋转和缩放矩阵并将其相乘。 But I can't seem to figure it how to build the rotation matrix and scale it properly. 但是我似乎无法弄清楚它如何构建旋转矩阵并正确缩放它。

Here's what I'm doing: 这是我在做什么:

glm::mat4 scale = glm::scale(mat4(1.0f), my_models[i].myscale);
glm::mat4 rotateM(1.0); 
glm:mat4 translate = glm::translate(mat4(1.0f), my_models[i].initialPos);

rotateM = mat4_cast(my_models[i].Quat); 
rotateM = glm::rotate(rotateM, (float) my_models[i].angle * t, my_models[i].animation_axis[0]);

my_models[i].modelMatrix = translate * rotateM *scale;
my_models[i].Quat = quat_cast(my_models[i].modelMatrix); 

In the Constructor I'm using: 在构造函数中,我正在使用:

quat Quat = glm::angleAxis(glm::radians(90.f), glm::vec3(0.f, 1.f, 0.f));

If my_models[i].myscale exactly 1.0f it rotates just fine, but if it is bigger the object keeps growing and rotates weirdly. 如果my_models [i] .myscale恰好为1.0f,它旋转就很好,但是如果它更大,则对象将继续增长并怪异地旋转。 Quaternions are very new to me, so I'm assuming I'm messing up there. 四元数对我来说很新,所以我假设我在搞砸。

What am I missing? 我想念什么? Are there simpler ways to construct the models rotation matrix? 有没有更简单的方法来构建模型旋转矩阵? if so, what information should I be saving? 如果是这样,我应该保存什么信息?

Edit: As jparima suggested, the following fixed my problem. 编辑:正如jparima建议,以下解决了我的问题。

glm::mat4 scale = glm::scale(mat4(1.0f), my_models[i].myscale);
glm::mat4 rotateM(1.0); 
glm::mat4 translate = glm::translate(mat4(1.0f), my_models[i].initialPos);

my_models[i].Quat = rotate(my_models[i].Quat, my_models[i].angle * t, my_models[i].animation_axis[0]);

rotateM = mat4_cast(my_models[i].Quat); 

my_models[i].modelMatrix = translate * rotateM * scale;

From the GLM quaternion.hpp for quat_cast it says 从GLM quaternion.hpp获得quat_cast它说

Converts a pure rotation 4 * 4 matrix to a quaternion. 将纯旋转4 * 4矩阵转换为四元数。

You are setting the whole model matrix there which has also scale and translation. 您要在那里设置整个模型矩阵,该矩阵也具有缩放和平移。 In fact, I don't know why you are converting a matrix to quaternion at all. 实际上,我根本不知道为什么要将矩阵转换为四元数。 Therefore you could remove the last line ( quat_cast ) and update the quaternion directly if you want to apply rotations. 因此,如果要应用旋转,则可以删除最后一行( quat_cast )并直接更新四元数。

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

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