c++ - 平行于全局轴的矩阵旋转
问题描述
现在我正在对对象进行以下转换:
- 沿 X 轴旋转
- 沿 Y 轴旋转
- 沿 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。
- 我沿 X 轴旋转对象。
- 然后沿 Y 轴旋转。
- 然后通过沿 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,但不是全局轴。
解决方案
为什么会发生这种情况 [...]
矩阵乘法不是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;
推荐阅读
- javascript - 使用 javascript 进行表单验证 - event.target.form.classList 未定义 - css 技巧教程
- c++ - 将基类传递给接收超类的函数委托
- javascript - 如何处理音频流
- java - 如何连续运行一个Java jar?
- django-models - 使用 Serialzer 使用 POST 方法更新 Django 模型实例
- python-3.x - 如何使第一个 for 语句出现在新行上
- python - 如何使用 GEKKO 和 APPT 检查求解器收敛性
- python-3.x - 如何更改由python中列表初始化的矩阵中的单个元素?
- python - 字典值到键
- node.js - Google Videointelligence API - UnhandledPromiseRejectionWarning,每分钟请求数