Three.js implements the model, and the model material can be dragged with DragControls

Three.js provides a drag API DragControls for achieving model material drag effects.

DragControls: is an auxiliary class used to implement drag control in Three.js. It simplifies the process of implementing dragging objects in Three.js.

The constructor of DragControls accepts three parameters:

objects: An array containing the objects that need to be dragged.
camera: camera object, used to convert screen coordinates into three-dimensional space coordinates.
domElement: The DOM element of the renderer, used to listen for mouse events.

DragControls instances provide the following methods and events:

addEventListener(type, listener): Add event listener. Supported event types include 'dragstart', 'drag' and 'dragend'.
removeEventListener(type, listener): Remove event listener.
dispose(): Release the DragControls instance and clear the event listener.
DragControls instances also automatically handle mouse events and trigger corresponding events. When the user starts dragging the object, the 'dragstart' event will be triggered; when the object is being dragged, the 'drag' event will be triggered; when the user stops dragging the object, the 'dragend' event will be triggered.

In the event listener, the dragged object can be obtained through event.object, and the position of the object during the dragging process can be obtained through event.position.

Note: The material type that DragControls supports dragging is type = "Mesh". Other types of materials may not have actual effects.

Based on the previous article Three.js loading external glb, fbx, gltf, obj model files, a new setModelMeshDrag (setting model material draggable method) is added
to introduce the drag API DragControls

import {
    
     DragControls } from 'three/examples/jsm/controls/DragControls';
	// 模型材质可拖拽
	setModelMeshDrag() {
    
    
	       const modelMaterialList= []
	       // 获取到需要拖拽的模型材质
  		   this.model.traverse((v) => {
    
    
			 if (v.isMesh && v.material && v.type=="Mesh") {
    
    
				   modelMaterialList.push(v)	
			    }
		    })
		    // 创建拖拽实列
			this.dragControls = new DragControls(this.modelMaterialList, this.camera, this.renderer.domElement);
			// 拖拽事件监听
			this.dragControls.addEventListener('dragstart', () => {
    
    
			    // 设置控制器不可操作
				this.controls.enabled = false
			})
			this.dragControls.addEventListener('dragend', () => {
    
    
				this.controls.enabled = true
			})
	}

The complete code can be found at: https://gitee.com/ZHANG_6666/Three.js3D

Interface effect
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_43835425/article/details/132557804