three.js 进阶
😋 Three.js 高级功能及性能优化
2022/6/05 10:03:00
➡️

性能优化

多个几何体合并为一个几何体

import * as BufferGeometryUtils from 'three/examples/jsm/utils/BufferGeometryUtils'


const geo = new THREE.BoxGeometry(1, 1, 1)
const geo1 = new THREE.BoxGeometry(2, 2, 2)
geo1.translate(1.5, 0, 0);

//第二个参数为 true,表示材质参数传入数组,顺序和几何体的顺序保持一致
//合并多个几何体为一个几何体,本质是顶点的合并
const mergedGeometries = BufferGeometryUtils.mergeBufferGeometries([geo, geo1], true)
//重置几何体的中心点
mergedGeometries.center()

const singleMergeMesh = new THREE.Mesh(mergedGeometries, [
  new THREE.MeshLambertMaterial({ color: 'red' }),
  new THREE.MeshLambertMaterial({ color: 'pink' }),
]
)

addObjectToScene([singleMergeMesh])

WebWorker

拖拽

还没有整合

import { TransformControls } from 'three/examples/jsm/controls/TransformControls'
import { DragControls } from 'three/examples/jsm/controls/DragControls'

if (camera.current && mainCanvas.current) {
  const transformControls = new TransformControls(camera.current, mainCanvas.current);
  addObjectToScene([transformControls])

  //单纯的拖拽没有任何参考,在3维空间内没有任何意义
  const dragControls = new DragControls([singleMergeMesh], camera.current, mainCanvas.current)
  // 鼠标略过事件
  dragControls.addEventListener('hoveron', function (event) {
    transformControls.attach(event.object)
  });

  //开始拖拽
  dragControls.addEventListener('dragstart', function (event) {
    //抑制相机控制器
    setIsUseOrbitControls(false)
  });

  //拖拽中
  dragControls.addEventListener('drag', function (event) {
    
  });

  //拖拽结束
  dragControls.addEventListener('dragend', function (event) {
    transformControls.detach()
    setIsUseOrbitControls(true)
    render()
  });
}
👍🎉🎊