需求:
拖动场景内的模型
方案:
增加控制器DragControls
1、引入控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; import { TransformControls } from "three/examples/jsm/controls/TransformControls"; import { DragControls } from "three/examples/jsm/controls/DragControls";
2、加载控制器
获取场景内模型列表 ——》
var objects = []; for (let i = 0; i < this.scene.children.length; i++) { if (this.scene.children[i].isMesh) { objects.push(this.scene.children[i]); } }
加载控制器TransformControls ——》
加载控制器DragControls ——》
this.transformControls = new TransformControls(this.camera, this.renderer.domElement); this.scene.add(this.transformControls) this.dragControls = new DragControls(objects, this.camera, this.renderer.domElement);
3、更改模型位置 ——》
可选监听:
dragstart 开始移动
drag
dragend 结束移动
hoveron 鼠标进入模型
hoveroff 鼠标离开模型
this.dragControls.addEventListener('hoveron', function( event ){ self.orbitControls.enabled = false self.changeMaterial(event.object) console.log(event.object) self.transformControls.attach(event.object); self.transformControls.setSize(0.4); });
createevent() { // 事件管理、操作控制器 ,旋转控件 this.orbitControls = new OrbitControls( this.camera, this.renderer.domElement ); // this.controls = new TrackballControls(this.camera, this.renderer.domElement); // 轨迹球控件 // // controls.noRotate = true; // this.controls.noPan = true; // // 视角最小距离 // this.controls.minDistance = 1000; // // 视角最远距离 // this.controls.maxDistance = 5000; this.orbitControls.enableDamping = true; this.orbitControls.maxDistance = 1000; this.orbitControls.minDistance = 1; this.transformControls = new TransformControls(this.camera, this.renderer.domElement); this.scene.add(this.transformControls) var objects = []; for (let i = 0; i < this.scene.children.length; i++) { if (this.scene.children[i].isMesh) { objects.push(this.scene.children[i]); } } this.dragControls = new DragControls(objects, this.camera, this.renderer.domElement); var self = this this.dragControls.addEventListener('dragstart', function (event) { // // this.controls.enabled = false; }); // 拖拽结束 this. dragControls.addEventListener('dragend', function (event) { // this.controls.enabled = true; }); this.dragControls.addEventListener('hoveron', function( event ){ //选中模型 self.orbitControls.enabled = false // 关闭orbitControls 控制器 self.changeMaterial(event.object) console.log(event.object) self.transformControls.attach(event.object); self.transformControls.setSize(0.4); }); this.dragControls.addEventListener('hoveroff',function(event){ 离开模型 self.modelnumber = event.object.position self.orbitControls.enabled = true //启动orbitControls 控制器 }) },