Skip to content

🎯 矩阵变换与gl-matrix4详解 ​

🔰 基础概念 ​

为什么需要矩阵? ​

在3D图形开发中,矩阵是实现物体变换(平移、旋转、缩放)的核心工具。通过矩阵运算,我们可以高效地处理复杂的空间变换。

📐 矩阵表示法 ​

1. 列向量表示法(Column-Major) ​

OpenGL/WebGL采用的标准表示法

js
[
    1, 0, 0, tx,  // 第一列
    0, 1, 0, ty,  // 第二列
    0, 0, 1, tz,  // 第三列
    0, 0, 0, 1    // 第四列
]

2. 行向量表示法(Row-Major) ​

DirectX等系统采用的表示法

js
[
     1,  0,  0,  0,  // 第一行
     0,  1,  0,  0,  // 第二行
     0,  0,  1,  0,  // 第三行
    tx, ty, tz,  1   // 第四行
]

🛠️ 矩阵工具类实现 ​

自定义mat4工具类 ​

这个实现展示了基本的矩阵操作:

js
const mat4 = {
    // 创建单位矩阵
    create() {
        return [
            1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            0, 0, 0, 1
        ];
    },

    // 创建平移矩阵
    translation(tx, ty, tz) {
        return [
            1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            tx, ty, tz, 1  // 平移分量在最后一行
        ];
    },

    // 创建缩放矩阵
    scaling(sx, sy, sz) {
        return [
            sx, 0,  0,  0,  // 对角线上是缩放因子
            0, sy,  0,  0,
            0,  0, sz,  0,
            0,  0,  0,  1,
        ];
    },
    
    // ... 其他代码保持不变 ...
};

🚀 gl-matrix4实战应用 ​

⚡ 重要概念 ​

gl-matrix采用**后乘(Post-Multiplication)**方式,这意味着:

  • 新的变换矩阵会被乘在右边
  • 变换顺序与数学公式的右乘顺序一致
  • 不是按照顶点操作的直观顺序

📝 基础操作示例 ​

1. 创建4x4矩阵 ​

js
// 创建平移矩阵 (x+1, y+2, z+3)
const mat4T = glMatrix.mat4.fromValues(
    1,0,0,0,  // 第一列
    0,1,0,0,  // 第二列
    0,0,1,0,  // 第三列
    1,2,3,1   // 第四列(平移量)
);

2. 常用变换操作 ​

js
// 创建基础矩阵
const baseMatrix = glMatrix.mat4.create();

// 🔄 平移变换
const translatedMatrix = glMatrix.mat4.translate(
    glMatrix.mat4.create(), 
    baseMatrix, 
    [2,0,0]  // x方向平移2个单位
);

// 📏 缩放变换
const scaledMatrix = glMatrix.mat4.scale(
    glMatrix.mat4.create(),
    baseMatrix,
    [10,1,1]  // x方向放大10倍
);

🎨 实际应用场景 ​

模型矩阵的构建 ​

js
// 创建最终的模型矩阵
const modelMatrix = glMatrix.mat4.create();

// 按顺序应用变换(注意是后乘)
glMatrix.mat4.multiply(modelMatrix, modelMatrix, scaleMatrix);  // 先缩放
glMatrix.mat4.multiply(modelMatrix, modelMatrix, rotateMatrix); // 再旋转
glMatrix.mat4.multiply(modelMatrix, modelMatrix, translateMatrix); // 最后平移

📚 常用API速查表 ​

方法描述示例
create()创建单位矩阵const mat = glMatrix.mat4.create()
translate()平移变换mat4.translate(out, a, [x,y,z])
scale()缩放变换mat4.scale(out, a, [sx,sy,sz])
rotate()旋转变换mat4.rotate(out, a, rad, axis)

💡 最佳实践 ​

  1. 始终记住矩阵乘法的顺序很重要
  2. 使用create()创建新矩阵而不是直接修改现有矩阵
  3. 对于复杂变换,先在纸上画出变换步骤
  4. 善用gl-matrix提供的辅助方法

📖 参考资料 ​