useAnimation
Manages animation playback for GLTF/GLB models. Wraps drei's useAnimations with play/pause, speed control, looping, and crossfade support.
You typically don't need this hook directly — the `Actor` component with `type="model"` handles animations via its props. Use this hook when you need programmatic control (e.g. crossfading between animations on user input).
Import #
tsx
import { useAnimation } from "@carverjs/core/hooks";Signature #
ts
function useAnimation(
clips: AnimationClip[],
options?: UseAnimationOptions
): UseAnimationReturn;Parameters #
| Parameter | Type | Description |
|---|---|---|
clips | AnimationClip[] | Animation clips from a loaded GLTF (gltf.animations) |
options | UseAnimationOptions | Playback configuration (optional) |
UseAnimationOptions #
| Field | Type | Default | Description |
|---|---|---|---|
clipName | string | — | Name of the clip to play. Changing this switches animations with a 0.2s crossfade |
paused | boolean | false | Pause/resume the active animation |
speed | number | 1 | Playback speed multiplier (applied to the mixer's timeScale) |
loop | boolean | true | true = LoopRepeat (infinite), false = LoopOnce (clamps when finished) |
Return Value (UseAnimationReturn) #
| Field | Type | Description |
|---|---|---|
ref | RefObject<Object3D> | Attach to the animated object (passed to <primitive ref={ref}>) |
clipNames | string[] | List of available animation clip names |
activeAction | AnimationAction | null | Currently playing action |
mixer | AnimationMixer | The underlying Three.js mixer |
actions | Record<string, AnimationAction | null> | All actions keyed by clip name |
play(name) | (name: string) => void | Play a clip by name (crossfades from current) |
stopAll() | () => void | Stop all running animations |
crossFadeTo(name, duration?) | (name: string, duration?: number) => void | Smoothly 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.