1. @threlte/extras
  2. useGltfAnimations



Convenience hook to use animations loaded with a <GLTF> threlte component.

Model: Littlest Tokyo by Glen Fox, CC Attribution.



Github View Source Code


NPM View Package

This hook needs context. Use only in a child component to <Canvas>.


Basic Example

<script lang="ts">
  import { GLTF, useGltfAnimations } from '@threlte/extras'
  // `useGltfAnimations` returns stores that populate
  // when the `<GLTF>` component finished loading.
  const { gltf, actions, mixer } = useGltfAnimations<'All Animations'>(({ actions, mixer }) => {
    // Either play your animations as soon as they are loaded
    mixer.timeScale = 0.5
    actions['All Animations']?.play()

  // Or play them whenever you need
  export const triggerAnimation = () => {
    if ($mixer) $mixer.timeScale = 0.5
    $actions['All Animations']?.play()

<!-- Bind the store `gltf` -->
<GLTF url={'/Bengal.glb'} bind:gltf={$gltf} />

Using the useGltf Hook

Sometimes you might want to use the hook useGltf to reuse parts of a model or use the embedded camera. In this case, the hook useGltf returns an object with a property gltf which you can pass as the first argument to the hook useGltfAnimations.

<script lang="ts">
  import { Object3DInstance } from '@threlte/core'
  import { useGltfAnimations, useGltf } from '@threlte/extras'

  // In this example, the useGltf hook returns a Writable<THREE.GLTF> store
  const { gltf } = useGltf('/path/to/model.glb')

  // Provide that store to the hook useGltfAnimations
  useGltfAnimations<'All Animations'>(gltf, ({ actions }) => {
    actions['All Animations']?.play()

{#if $gltf}
  <Object3DInstance object={$gltf.scene} />