从零开始学习three.js(21):一文详解three.js中的矩阵Matrix和向量Vector
一、三维世界的数学基石
在Three.js的三维世界里,所有视觉效果的实现都建立在严密的数学基础之上。其中向量(Vector) 和矩阵(Matrix) 是最核心的数学工具,它们就像构建数字宇宙的原子与分子,支撑着物体的移动、旋转、缩放以及复杂的空间变换。本文一文详解向量(Vector) 和矩阵(Matrix)。
1.1 向量:三维空间的基本元素
向量是描述空间方向和位置的数学实体,在Three.js中主要使用以下三种向量类型:
// 三维向量(最常用)
const position = new THREE.Vector3(1, 2, 3);// 二维向量(用于UV映射)
const uvCoord = new THREE.Vector2(0.5, 0.5);// 四维向量(颜色RGBA或特殊计算)
const color = new THREE.Vector4(1, 0, 0, 0.5);
核心操作示例:
// 向量加法(物体位移)
const v1 = new THREE.Vector3(1, 2, 3);
const v2 = new THREE.Vector3(4, 5, 6);
v1.add(v2); // (5,7,9)// 点积计算(光照计算)
const lightDir = new THREE.Vector3(0, 1, 0).normalize();
const normal = new THREE.Vector3(0, 0, 1);
const dotProduct = lightDir.dot(normal); // 0// 叉乘应用(计算法线)
const tangent = new THREE.Vector3(1, 0, 0);
const bitangent = new THREE.Vector3(0, 1, 0);
const normal = tangent.cross(bitangent); // (0,0,1)
1.2 矩阵:空间变换
Three.js中的矩阵主要用于描述空间变换关系,以下是关键矩阵类型:
矩阵类型 | 维度 | 应用场景 |
---|---|---|
Matrix3 | 3x3 | UV变换、法线矩阵 |
Matrix4 | 4x4 | 模型视图投影矩阵(核心) |
Matrix4数组 | - | 实例化渲染 |
二、矩阵运算的奥秘
2.1 基础矩阵操作
// 创建单位矩阵(所有矩阵变换的起点)
const identityMat = new THREE.Matrix4().identity();// 矩阵相乘(变换组合)
const rotateMat = new THREE.Matrix4().makeRotationX(Math.PI/2);
const translateMat = new THREE.Matrix4().makeTranslation(0, 5, 0);
const finalMat = translateMat.multiply(rotateMat); // 注意顺序!// 矩阵求逆(坐标系转换)
const viewMatrix = camera.matrixWorldInverse;
2.2 矩阵分解技巧
const matrix = new THREE.Matrix4();
const position = new THREE.Vector3();
const quaternion = new THREE.Quaternion();
const scale = new THREE.Vector3();matrix.decompose(position, quaternion, scale);
console.log('Position:', position);
console.log('Rotation:', quaternion);
console.log('Scale:', scale);
三、矩阵变换实战指南
3.1 变换组合原理
Three.js采用后乘的矩阵组合方式,理解执行顺序至关重要:
const mesh = new THREE.Mesh(geometry, material);// 正确的变换顺序:缩放 -> 旋转 -> 平移
mesh.scale.set(2, 2, 2);
mesh.rotation.x = Math.PI/4;
mesh.position.y = 10;// 等效矩阵计算:
const scaleMat = new THREE.Matrix4().makeScale(2, 2, 2);
const rotateMat = new THREE.Matrix4().makeRotationX(Math.PI/4);
const translateMat = new THREE.Matrix4().makeTranslation(0, 10, 0);// 矩阵组合顺序:T * R * S
const finalMatrix = translateMat.multiply(rotateMat).multiply(scaleMat);
mesh.matrix = finalMatrix;
3.2 矩阵堆栈管理
在复杂层级结构中,矩阵需要逐级传递:
function updateWorldMatrices(object, parentMatrix) {if (!parentMatrix) parentMatrix = new THREE.Matrix4();// 计算本地矩阵object.updateMatrix();// 组合世界矩阵object.matrixWorld.multiplyMatrices(parentMatrix, object.matrix);// 递归处理子对象for (let child of object.children) {updateWorldMatrices(child, object.matrixWorld);}
}
四、关键矩阵系统解析
4.1 模型视图投影矩阵(MVP)
// 获取三个关键矩阵
const modelMatrix = mesh.matrixWorld;
const viewMatrix = camera.matrixWorldInverse;
const projectionMatrix = camera.projectionMatrix;// 组合MVP矩阵
const mvpMatrix = new THREE.Matrix4().multiplyMatrices(projectionMatrix, viewMatrix).multiply(modelMatrix);
4.2 法线矩阵(Normal Matrix)
const normalMatrix = new THREE.Matrix3();
normalMatrix.getNormalMatrix(modelViewMatrix);// 在着色器中使用
material.onBeforeCompile = (shader) => {shader.uniforms.normalMatrix = { value: normalMatrix };shader.vertexShader = `uniform mat3 normalMatrix;${shader.vertexShader}`.replace('#include <beginnormal_vertex>', `objectNormal = normalMatrix * objectNormal;`);
};
五、性能优化策略
5.1 矩阵更新优化
// 禁用自动矩阵更新
mesh.matrixAutoUpdate = false;// 手动批量更新
function updateScene() {objects.forEach(obj => {obj.updateMatrix();obj.updateMatrixWorld(true); // 跳过子对象更新});
}
5.2 矩阵缓存重用
const _tempMatrix = new THREE.Matrix4();function calculateTransform(position, rotation, scale) {return _tempMatrix.compose(position, rotation, scale).clone();
}
六、常见问题诊断
6.1 变换顺序错误
症状:物体缩放导致旋转轴偏移
解决方案:
// 错误方式:
mesh.position.set(0, 5, 0);
mesh.rotation.y = Math.PI/2;
mesh.scale.set(2, 2, 2);// 正确方式:
mesh.scale.set(2, 2, 2);
mesh.rotation.y = Math.PI/2;
mesh.position.set(0, 5, 0);
6.2 矩阵更新遗漏
症状:子对象未跟随父级移动
解决方案:
parent.add(child);
parent.matrixWorldNeedsUpdate = true; // 强制更新世界矩阵
七、高阶应用实例
7.1 自定义矩阵动画
function matrixAnimation(mesh, duration) {const startMatrix = mesh.matrix.clone();const endMatrix = new THREE.Matrix4().makeRotationY(Math.PI).multiply(new THREE.Matrix4().makeTranslation(5, 0, 0));new TWEEN.Tween({ t: 0 }).to({ t: 1 }, duration).onUpdate(({ t }) => {mesh.matrix = startMatrix.clone().lerp(endMatrix, t);mesh.matrixWorldNeedsUpdate = true;}).start();
}
7.2 GPU矩阵计算
// 顶点着色器中使用自定义矩阵
const material = new THREE.ShaderMaterial({uniforms: {customMatrix: { value: new THREE.Matrix4() }},vertexShader: `uniform mat4 customMatrix;void main() {gl_Position = projectionMatrix * modelViewMatrix * customMatrix * vec4(position, 1.0);}`
});
八、调试与可视化工具
8.1 矩阵可视化
function printMatrix(label, matrix) {console.log(`${label}:`);const te = matrix.elements;for (let i = 0; i < 4; i++) {console.log(te[i*4].toFixed(2), te[i*4+1].toFixed(2),te[i*4+2].toFixed(2),te[i*4+3].toFixed(2));}
}
8.2 坐标系辅助显示
const axisHelper = new THREE.AxesHelper(5);
mesh.add(axisHelper);// 实时显示世界坐标系
function updateAxisHelper() {axisHelper.matrixWorld.copy(mesh.matrixWorld);axisHelper.matrixWorld.decompose(axisHelper.position,axisHelper.quaternion,axisHelper.scale);
}
九、最佳实践总结
- 优先使用高层API:尽量通过
position
、rotation
、scale
属性操作对象 - 谨慎直接修改矩阵:仅在必要时直接操作矩阵元素
- 注意更新顺序:修改属性后及时调用
updateMatrix()
- 重用矩阵对象:避免频繁创建新矩阵实例
- 理解空间转换链:
局部坐标 -> 世界坐标 -> 视图坐标 -> 裁剪坐标
通过掌握矩阵与向量的奥秘,开发者可以:
✅ 实现精准的物理碰撞检测
✅ 创建电影级动态光影效果
✅ 构建工业级数字孪生系统
✅ 开发复杂机械运动仿真
建议结合Three.js官方文档中的Matrix4和Vector3API参考进行实践,并利用浏览器开发者工具实时观察矩阵变化。