Three.js - 网格组示例? (三.Object3D() 高级)

问题描述 投票:0回答:2

我试图了解如何将子网格分组/链接到父网格。我希望能够:

  • 拖动父级
  • 相对于父元素旋转子元素
  • 让家长轮换/翻译为孩子做正确的事

我唯一的背景是在《第二人生》中使用 LSL 来操作对象中的链接 prims。我想我不想合并网格,因为我想保持对每个子项的控制(悬停、纹理、旋转、缩放等)。

有什么好的教程吗?这是通过 THREE.Object3D() 实现的,是吗?

谢谢,丹尼尔

object parent-child mesh three.js
2个回答
59
投票

拖动会有点棘手,因为您需要计算出鼠标在屏幕(屏幕空间)上的 x/y 位置在 3D 世界中的位置,然后您需要投射一条射线并检查是否它与您要拖动的对象相交。我想这将是一个不同的问题。

设置对象层次结构相当简单。 正如您所暗示的,您将使用 THREE.Object3D 实例将对象嵌套到使用它的 add() 方法中。这个想法是,您将为具有几何形状的对象和 Object3D 实例使用网格,您只需要在其中嵌套元素即可。

group = new THREE.Object3D();//create an empty container
group.add( mesh );//add a mesh with geometry to it
scene.add( group );//when done, add the group to the scene

更新

正如 Nick Desaulniers 和 escapedcat 指出的那样,

THREE.Group
现在提供了您需要的功能。包含的代码示例:

const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
    
const cubeA = new THREE.Mesh( geometry, material );
cubeA.position.set( 100, 100, 0 );
    
const cubeB = new THREE.Mesh( geometry, material );
cubeB.position.set( -100, -100, 0 );
    
// Create a group and add the two cubes
// These cubes can now be rotated / scaled etc as a group
const group = new THREE.Group();
group.add( cubeA );
group.add( cubeB );
    
scene.add( group );

15
投票

另一种方式,因为网格也可以是父级:

meshParent.add(meshChild1);
meshParent.add(meshChild2);
scene.add(meshParent);

mesh1.add(mesh2); // "mesh2" only manipulates itself
mesh3.add(mesh1); // "mesh1" manipulates itself and mesh2
scene.add(mesh3); // "mesh3" manipulates all meshes
© www.soinside.com 2019 - 2024. All rights reserved.