使用Three.js拖放加载GLTF对象

4

我尝试加载由多个元素组成的gltf(对象),当我尝试选择并拖动该对象时,我只能拖动一个元素。请帮助我解决这个问题。

var loader = new THREE.GLTFLoader();
loader.load(‘W3030 / W3030.gltf’, (gltf) => {
  this.scene.add(gltf.scene);
  gltf.scene.scale.set(1, 1, 1);
  gltf.scene.traverse(function(object) {
    if (object.isMesh) objects.push(object);
    if (object.isMesh) objects.castShadow = true;
  });
});

GLTF演示截图:

拖拽前:https://prnt.sc/pu940g

拖拽后:https://prnt.sc/pu93g3

2个回答

2
即使您加载单个glTF资产,视觉对象也可以由许多个单独的3D对象组成。由于THREE.DragControls在对象级别上工作,因此所述结果是预期的行为。
解决此问题的最简单方法是在诸如Blender之类的内容创建工具中合并对象的单个部分,然后导出新的glTF。否则,您必须通过three.js将单个网格合并为一个更大的网格。或者您可以更改THREE.DragControls,以便它也能够基于其边界框选择组对象。 three.js R113

1
use following code to drag multi mesh GLTF. It is Work for me.

 var dragobjects =[];
 //add following code in init function
 var gltfobject = addGLTFObjectIntoScene();
 scene.add(gltfobject);

dragControls = new THREE.DragControls(dragobjects, camera, renderer.domElement);
dragControls.addEventListener('dragstart', onDragStart, false);
dragControls.addEventListener('drag', onDrag , false);
dragControls.addEventListener('dragend', onDragEnd, false);

//结束初始化函数的代码 //在初始化函数前或后添加以下函数

 function drawBox(objectwidth,objectheight,objectdepth){
 var geometry, material, box;
 geometry = new THREE.BoxGeometry(objectwidth,objectheight,objectdepth);
 material = new THREE.MeshBasicMaterial({color: 0xffff00, transparent: true, opacity: 0,depthTest:false});
 box = new THREE.Mesh(geometry, material);
 dragobjects.push(box);
 box.position.set(0, 0, 0);
 return box;
};  
function addGLTFObjectIntoScene(){ 
 group = new THREE.Group();
 var loader = new THREE.GLTFLoader();
 loader.load( 'W1230/W1230.gltf', ( gltf ) => {
    mesh = gltf.scene;
    mesh.scale.set( 30, 30, 30);
    var gltfbox = new THREE.Box3().setFromObject( mesh );
    var objectwidth = Math.floor(gltfbox.getSize().x);
    var objectheight = Math.floor(gltfbox.getSize().y);
    var objectdepth = Math.floor(gltfbox.getSize().z);
    objectwidth = objectwidth + parseInt(2);
    objectheight = objectheight + parseInt(2);
    objectdepth  = objectdepth + parseInt(1);
    mesh.position.set(0, -objectheight/2, 0);
    box  = drawBox(objectwidth,objectheight,objectdepth); 
    group.add(box);
    group.name = "quadrant";
    console.log(mesh);
    box.add( mesh);
 });
 return group;
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接