useAnimation

Manages animation playback for GLTF/GLB models. Wraps drei's useAnimations with play/pause, speed control, looping, and crossfade support.

Import #

tsx
import { useAnimation } from "@carverjs/core/hooks";

Signature #

ts
function useAnimation(
  clips: AnimationClip[],
  options?: UseAnimationOptions
): UseAnimationReturn;

Parameters #

ParameterTypeDescription
clipsAnimationClip[]Animation clips from a loaded GLTF (gltf.animations)
optionsUseAnimationOptionsPlayback configuration (optional)

UseAnimationOptions #

FieldTypeDefaultDescription
clipNamestringName of the clip to play. Changing this switches animations with a 0.2s crossfade
pausedbooleanfalsePause/resume the active animation
speednumber1Playback speed multiplier (applied to the mixer's timeScale)
loopbooleantruetrue = LoopRepeat (infinite), false = LoopOnce (clamps when finished)

Return Value (UseAnimationReturn) #

FieldTypeDescription
refRefObject<Object3D>Attach to the animated object (passed to <primitive ref={ref}>)
clipNamesstring[]List of available animation clip names
activeActionAnimationAction | nullCurrently playing action
mixerAnimationMixerThe underlying Three.js mixer
actionsRecord<string, AnimationAction | null>All actions keyed by clip name
play(name)(name: string) => voidPlay a clip by name (crossfades from current)
stopAll()() => voidStop all running animations
crossFadeTo(name, duration?)(name: string, duration?: number) => voidSmoothly transition to another clip. Default duration: 0.3s

Usage #

Declarative (via options) #

tsx
const { ref } = useAnimation(gltf.animations, {
  clipName: "Run",
  speed: 1.5,
  loop: true,
});

return <primitive object={gltf.scene} ref={ref} />;

Programmatic control #

tsx
const { ref, play, stopAll, crossFadeTo, clipNames } = useAnimation(gltf.animations);

// Switch animation on keypress
useEffect(() => {
  const onKey = (e: KeyboardEvent) => {
    if (e.key === "w") crossFadeTo("Run", 0.3);
    if (e.key === "s") play("Idle");
    if (e.key === " ") stopAll();
  };
  window.addEventListener("keydown", onKey);
  return () => window.removeEventListener("keydown", onKey);
}, [play, stopAll, crossFadeTo]);

return <primitive object={gltf.scene} ref={ref} />;

Type Definitions #

See Types for UseAnimationOptions and UseAnimationReturn definitions.