threlte logo
@threlte/core

<HierarchicalObject>

This is a trait component. Trait components are mostly used internally and make certain aspects of three.js objects accessible and reactive and interact with Threlte systems. It’s an advanced feature and you should only use it if you know what you’re doing.

On initialization, the component <HierarchicalObject> forwards a provided THREE.Object3D to a parent <HierarchicalObject> component. The parent <HierarchicalObject> receives this object in the callback onChildMount to e.g. add the object to the scene graph, create a list of all child objects or use the child objects and act on their geometries.

The component <SceneGraphObject> in turn uses this component to add and remove objects to and from the scene graph.

Basic Example

In this example the component is responsible for

  • forwarding the mesh to the parent <HierarchicalObject>
  • adding children to the scene graph (i.e. as children to the mesh)
  • removing children from the scene graph
@@ -86,23 +117,41 @@ The component `<HierarchicalObject>` also provides a useful binding to collect a

<HierarchicalObject
  object={mesh}
  bind:children
>
  <slot />
</HierarchicalObject>

Mounting a component to a different parent

Sometimes you need to add a component as a child to another object than its parent. Let’s say we want to transform a THREE.Mesh object with TransformControls. In this case, Three.js wants you to mount the TransformControls as a child to the scene and attach it to the THREE.Mesh. We can use the <HierarchicalObject> component to add an object to an arbitrary parent object:

<script>
  import { HierarchicalObject, useThrelte } from '@threlte/core'
  import { TransformControls } from 'three/examples/jsm/controls/TransformControls'
  import { otherMesh } from '$stores/app' // let's say this is a store with a mesh

  const { scene } = useThrelte()
</script>

<HierarchicalObject
  onChildMount={(child) => {
    // child is the TransformControls object
    scene.add(child)
  }}
  onChildDestroy={(child) => {
    // child is the TransformControls object
    scene.remove(child)
  }}
>
  <T
    is={TransformControls}
    on:create={({ ref, cleanup }) => {
      ref.attach($otherMesh)
      cleanup(ref.detach)
    }}
  />
</HierarchicalObject>

Component Signature

Props

name
type
required
description

object
THREE.Object3D
no
If an object is provided, this object is passed to the upstream onChildMount and onChildDestroy methods.

onChildDestroy
(child: Object3D) => void
no
Will be invoked when a child is destroyed.

onChildMount
(child: Object3D) => void
no
Will be invoked when a child is mounted.

Bindings

name
type

children
Object3D[]