当前位置: 首页 > news >正文

从零开始学习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中的矩阵主要用于描述空间变换关系,以下是关键矩阵类型:

矩阵类型维度应用场景
Matrix33x3UV变换、法线矩阵
Matrix44x4模型视图投影矩阵(核心)
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);
}

九、最佳实践总结

  1. 优先使用高层API:尽量通过positionrotationscale属性操作对象
  2. 谨慎直接修改矩阵:仅在必要时直接操作矩阵元素
  3. 注意更新顺序:修改属性后及时调用updateMatrix()
  4. 重用矩阵对象:避免频繁创建新矩阵实例
  5. 理解空间转换链局部坐标 -> 世界坐标 -> 视图坐标 -> 裁剪坐标

通过掌握矩阵与向量的奥秘,开发者可以:
✅ 实现精准的物理碰撞检测
✅ 创建电影级动态光影效果
✅ 构建工业级数字孪生系统
✅ 开发复杂机械运动仿真

建议结合Three.js官方文档中的Matrix4和Vector3API参考进行实践,并利用浏览器开发者工具实时观察矩阵变化。

相关文章:

  • MyBatis:动态SQL
  • 中国城市间交通驾车距离矩阵(2024)
  • Oracle 中 open_cursors 参数详解:原理、配置与性能测试
  • Java 后端基础 Maven
  • Linux 移植 Docker 详解
  • uniapp小程序获取手机设备安全距离
  • Grafana之Dashboard(仪表盘)
  • OpenCV CUDA 模块中的矩阵算术运算-----在频域中执行两个复数频谱的逐元素乘法的函数mulSpectrums()
  • 多商户1.8.1版本前端问题优化集合指南
  • 可视化图解算法41:搜索二维矩阵(二维数组中的查找)
  • OpenCV CUDA模块中的矩阵算术运算------创建卷积操作对象的工厂方法 cv::cuda::createConvolution
  • 批量剪辑 + 矩阵分发 + 数字人分身源码搭建全技术解析,支持OEM
  • Linux 判断是否有未挂载的盘 分区挂载 (挂载所有大小的盘,包括挂载超过2T的盘)
  • Qt框架核心组件完全指南:从按钮交互到定时器实现
  • Regmap子系统之六轴传感器驱动-编写icm20607.c驱动
  • 基于STM32的光照测量报警Proteus仿真设计+程序设计+设计报告+讲解视频
  • 供应链风险管理中,企业如何识别关键风险因素?
  • 【C++】模版(1)
  • 机器学习--特征工程具体案例
  • 2022年下半年信息系统项目管理师——综合知识真题及答案(4)
  • 解读|俄方称愿与乌方共同起草和平备忘录,特朗普多轮通话外交有效吗?
  • 苏丹港持续遭无人机袭击,外交部:呼吁各方保护民用设施和平民安全
  • 上海这个咖啡文化节首次“走出去”,率本土品牌亮相英国伦敦
  • 女生“生理期请病假要脱裤子证明”?高校回应:视频经处理后有失真等问题
  • 大外交丨3天拿下数万亿美元投资,特朗普在中东做经济“加法”和政治“减法”
  • 嫩黑线货物列车脱轨致1名路外人员死亡,3人被采取刑事强制措施