程序开发过程中,有时候需要对已有的网格模型进行旋转、平移、缩放和投影等操作,在软件中可能就是点某个按钮,输入一些参数,就可以实现。今天木木带着大家看看程序里面是如何实现这些操作的。
需要引入一个重要的概念:坐标变换矩阵。是一种用于将点或对象的坐标从一个坐标系转换到另一个坐标系的数学工具。
在模型旋转操作过程中,常常需要用到旋转矩阵,旋转矩阵是一种正交矩阵,用于表示物体在空间中的旋转操作。对于三维空间,旋转矩阵是一个 ( ) 的矩阵,满足以下性质:
% 将旋转角度从度转换为弧度
theta = 90;
theta_rad = deg2rad(theta);
% 以 X 轴旋转的旋转矩阵
R_x = [1, 0, 0;
0, cos(theta_rad), -sin(theta_rad);
0, sin(theta_rad), cos(theta_rad)];
R_y = [cos(theta_rad), 0, sin(theta_rad);
0, 1, 0;
-sin(theta_rad), 0, cos(theta_rad)];
R_z = [cos(theta_rad), -sin(theta_rad), 0;
sin(theta_rad), cos(theta_rad), 0;
0, 0, 1];
多个旋转矩阵可以通过矩阵相乘来组合。例如,依次绕 Z 轴和 Y 轴旋转的总变换矩阵 ( ) 是:
注意:矩阵乘法是非交换的,旋转的顺序会影响结果。
% ------------------ 旋转节点坐标 ------------------
% 定义旋转角度(以度为单位)
theta_x = 60; % 绕 X 轴旋转角度
theta_y = 50; % 绕 Y 轴旋转角度
theta_z = 40; % 绕 Z 轴旋转角度
% 将旋转角度从度转换为弧度
theta_x_rad = deg2rad(theta_x);
theta_y_rad = deg2rad(theta_y);
theta_z_rad = deg2rad(theta_z);
% 绕 X 轴旋转的旋转矩阵
R_x = [1, 0, 0;
0, cos(theta_x_rad), -sin(theta_x_rad);
0, sin(theta_x_rad), cos(theta_x_rad)];
% 绕 Y 轴旋转的旋转矩阵
R_y = [cos(theta_y_rad), 0, sin(theta_y_rad);
0, 1, 0;
-sin(theta_y_rad), 0, cos(theta_y_rad)];
% 绕 Z 轴旋转的旋转矩阵
R_z = [cos(theta_z_rad), -sin(theta_z_rad), 0;
sin(theta_z_rad), cos(theta_z_rad), 0;
0, 0, 1];
% 依次应用 X, Y, Z 旋转
gNode = (R_z * R_y * R_x * gNode')'; % gNode为原模型节点坐标信息
% --------------------------------------------------