如何在Vue中使用Mapbox和Three.js确保三维物体的底部固定在地图上?

如何在Vue中使用Mapbox和Three.js确保三维物体的底部固定在地图上?

vue中Mapbox和Three.JS:实现3D模型与地图视角的完美适配

本文探讨如何在Vue.js应用中,结合Mapbox GL JS和Three.js,实现三维模型与地图视角的同步,确保模型底部始终固定在地图表面,不会因视角变化而偏移。这在构建地理信息系统或3D地图可视化应用中至关重要。

假设你已成功渲染3D立方体到Mapbox地图,但视角移动时立方体位置发生漂移。问题在于Three.js坐标系与Mapbox地图坐标系的转换和模型位置的设置。

以下代码片段展示了可能存在问题的代码结构,其中render函数更新Three.js相机矩阵,calculatemodeltransform函数进行坐标转换:

render: (gl, matrix) => {   const m = new THREE.Matrix4().fromArray(matrix);   const l = new THREE.Matrix4().makeTranslation(modelTransform.translateX, modelTransform.translateY, modelTransform.translateZ)       .scale(new THREE.Vector3(modelTransform.scale, -modelTransform.scale, modelTransform.scale))       .multiply(new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(1, 0, 0), modelTransform.rotateX))       .multiply(new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0, 1, 0), modelTransform.rotateY))       .multiply(new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0, 0, 1), modelTransform.rotateZ));   customLayer.camera.projectionMatrix = m.multiply(l);   customLayer.renderer.resetState();   customLayer.renderer.render(customLayer.scene, customLayer.camera);   customLayer.map.triggerRepaint(); },  calculatemodeltransform(point) {   const modelAsMercatorCoordinate = mapboxgl.MercatorCoordinate.fromLngLat([point.lng, point.lat], this.modelAltitude);   return {     translateX: modelAsMercatorCoordinate.x,     translateY: modelAsMercatorCoordinate.y,     translateZ: modelAsMercatorCoordinate.z,     rotateX: this.modelRotate[0],     rotateY: this.modelRotate[1],     rotateZ: this.modelRotate[2],     scale: modelAsMercatorCoordinate.meterInMercatorCoordinateUnits()   }; }

核心问题在于模型的translateZ以及模型创建时的垂直位置。 我们需要调整模型位置,使其底部与地图平面精确对齐。

立即学习前端免费学习笔记(深入)”;

解决方案:

  1. 模型创建调整: 在创建Three.js模型时,考虑模型高度,并调整其垂直位置(y轴)使其底部位于地图平面(通常y=0)。
// 创建一个正方体几何体,altitude 为模型高度 const geometry = new THREE.BoxGeometry(20, altitude, 20); const material = new THREE.MeshStandardMaterial({ color, transparent: true, opacity: 0.8 }); const cube = new THREE.Mesh(geometry, material);  // 关键步骤:将立方体底部放置在地图平面上 cube.position.y = altitude / 2; 
  1. render函数调整: 在render函数中,根据模型高度调整translateZ值,确保模型底部始终与地图平面对齐。
const l = new THREE.Matrix4().makeTranslation(modelTransform.translateX, modelTransform.translateY, modelTransform.translateZ - altitude / 2)   .scale(new THREE.Vector3(modelTransform.scale, -modelTransform.scale, modelTransform.scale))   // ... 其他转换矩阵

通过以上调整,即使地图视角变化,三维模型的底部也会保持在地图表面,实现完美的视角适配。 请确保altitude变量正确反映模型的高度。 如有需要,可以根据模型的实际几何形状进一步微调垂直位置。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享