首页 > 解决方案 > 平行于全局轴的矩阵旋转

问题描述

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

  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,但不是全局轴。

标签: c++openglglslglm-math

解决方案


为什么会发生这种情况 [...]

矩阵乘法不是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;

推荐阅读