平行于全局轴的矩阵旋转

Rotation of the matrices parallel to the global axes

现在我正在对对象进行以下转换:

  1. 沿X轴旋转
  2. 沿Y轴旋转
  3. 沿Z轴移动-2.5
//create model matrix
model_matrix = glm::mat4(1.0f);
//create view matrix
view_matrix = glm::mat4(1.0f);
//create projection matrix
projection_matrix = glm::mat4(1.0f);

//setting up model
model_matrix = glm::translate(model_matrix, glm::vec3(0, 0, -2.5));
//x_rot and y_rot are global variables.
y_rot += y_rotation_speed_in_degrees;
x_rot += x_rotation_speed_in_degrees;
model_matrix = glm::rotate(model_matrix, glm::radians(y_rot), glm::vec3(0, 1, 0));
model_matrix = glm::rotate(model_matrix, glm::radians(x_rot), glm::vec3(1, 0, 0));

//setting up projection
projection_matrix = glm::perspective(45.0f, (float)window_width / (float)window_height, 0.1f, 100.0f);

replication_matrix = projection_matrix * view_matrix * model_matrix;

为了旋转,我设置了(x/y)_rotation_speed_in_degrees.

  1. 我沿 X 轴旋转对象。
  2. 然后沿Y轴旋转。
  3. 然后通过沿X轴旋转,旋转发生在局部X轴上。

虽然绕 Y 轴旋转 (2),但 3 上的旋转发生在局部 X 轴上。

我希望看到这个

为什么会发生这种情况以及如何围绕全局轴进行所有旋转?


我正在尝试这样做:
我在头文件中声明模型和旋转矩阵

glm::mat4 model_matrix = glm::mat4(1.0f);
glm::mat4 rotation_matrix = glm::mat4(1.0f);

我在我的绘图周期中执行以下操作:

//create model matrix
model_matrix = glm::mat4(1.0f);
//create view matrix
view_matrix = glm::mat4(1.0f);
//create projection matrix
projection_matrix = glm::mat4(1.0f);

rotation_matrix = glm::rotate(rotation_matrix, glm::radians(y_rotation_speed_in_degrees), glm::vec3(0, 1, 0));
rotation_matrix = glm::rotate(rotation_matrix, glm::radians(x_rotation_speed_in_degrees), glm::vec3(1, 0, 0));

model_matrix = glm::translate(glm::mat4(1.0f), glm::vec3(0, 0, -2.5)) * rotation_matrix;

//setting up projection
projection_matrix = glm::perspective(45.0f, (float)window_width / (float)window_height, 0.1f, 100.0f);

replication_matrix = projection_matrix * view_matrix * model_matrix;

这就是我得到的:

沿局部轴旋转 2 和 3,而不是全局轴。

Why is this happening [...]

矩阵乘法不是Commutative。顺序很重要。

如果要逐步旋转对象,基于之前的旋转,必须存储模型矩阵并将新的旋转应用于存储的模型矩阵。您需要将模型矩阵保持在框架之外,而不是汇总旋转角度。

在应用程序循环之前,创建一个初始旋转矩阵:

rotation_matrix = glm::mat4(1.0f);

在应用程序循环中应用新的旋转并计算模型矩阵:

glm::mat4 rm_x = glm::rotate(glm::mat4(1.0f), 
    glm::radians(y_rotation_speed_in_degrees), glm::vec3(0, 1, 0));
glm::mat4 rm_y = glm::rotate(glm::mat4(1.0f), 
    glm::radians(x_rotation_speed_in_degrees), glm::vec3(1, 0, 0));
glm::mat4 rotation_matrix = rm_x * rm_y * rotation_matrix;

model_matrix = glm::translate(glm::mat4(1.0f), glm::vec3(0, 0, -2.5)) * rotation_matrix;