Skeleton and morphs
Updated
The Skeleton and Morph components hand the insides of a loaded model to your scripts. A skeleton is the hierarchy of bones (joints) that deforms a character’s mesh: move the Head bone and the head of the mesh follows. Morph targets, also called blend shapes, are alternative shapes of a mesh stored in the model, such as a mouth open or eyes closed; a weight from 0 to 1 blends between the base shape and the target.
With these components a script can animate procedurally: turn a head to look at the player, open a jaw while a character speaks, blink, or point a hand at a target, on top of a playing clip or instead of one.
| Component | Type | Script API | Holds |
|---|---|---|---|
| Skeleton | comp-skeleton |
bones(), bone(name), hasBones(), rig |
The model’s bones and, when configured, its humanoid mapping and limb chains. |
| Morph | comp-morph |
channels(), channel(name), hasChannels() |
The model’s morph targets, one channel per target name. |
Both go on a model entity (glTF, FBX, Collada, OBJ, USDZ or a kit piece), one of each per entity.
Before you start
Section titled “Before you start”- Bones are scene objects (
THREE.Bone), so you pose them withrotation,positionandquaternion, and read them withgetWorldPosition. TheTHREEglobal gives you vectors and other math helpers. - The order of a frame matters: timelines, then clips, then your
update, then dynamic bones. See Animation. - Scripts reach the components with
getComponent(SkeletonComponent)andgetComponent(MorphComponent).
How they bind
Section titled “How they bind”- Each reads the model once, as it loads, or as the component is added or switched on. Nothing is looked up a frame.
- Before the model loads, or while the component is off, they hold nothing:
bone()andchannel()returnundefined,bones()andchannels()are empty, andhasBones()andhasChannels()arefalse. - A model reload makes new bones and channels. Get them again after the model’s ready event (for a glTF,
EventType.GLTF.Ready) instead of keeping them across reloads.
Skeleton
Section titled “Skeleton”| Call | Returns |
|---|---|
bones() |
Every bone of the loaded model, in the model’s order. The same array on every call. |
bone(name) |
The bone name, or undefined when the model has no such bone. |
hasBones() |
Whether the loaded model has a bone. |
rig |
The humanoid mapping, when the rig prop is set and the model is loaded; otherwise undefined. |
bone() reads a name map built as the model loads, and bones() returns the same list each time: both are fine to call every frame.
Bone names
Section titled “Bone names”A loaded glTF changes node names: spaces become _, and ., :, / and square brackets are dropped. Blender’s Tail.001 loads as Tail001, and Upper Arm as Upper_Arm. bone(name) accepts either name.
Posing over clips
Section titled “Posing over clips”A clip that animates a bone writes it every frame, before your script’s update. So:
- A pose you write in
updatewins that frame. Write it every frame to hold it over the clip. - A pose you write once, in
startupor in an event, is overwritten by the clip’s next frame. - A dynamic bone on that bone then swings about your pose.
Humanoid rig
Section titled “Humanoid rig”Different models name their bones differently: Head, mixamorig:Head, npc_cranium. Setting the Skeleton’s rig prop to { type: 'humanoid' } maps the model’s joints to standard humanoid names, so one script works on many characters.
| Prop | Type | Default | Description |
|---|---|---|---|
rig |
{ type: 'humanoid', bones? } |
absent | The humanoid mapping. bones optionally maps humanoid names to the model’s bone names, such as { head: 'npc_; unmapped joints resolve automatically from the model’s metadata and common bone names. |
Member of skeleton.rig |
Returns |
|---|---|
rig. |
The joint for a humanoid name, or undefined. |
rig. |
[upper, lower, end] joints of leftArm, rightArm, leftLeg or rightLeg, when all three exist; otherwise undefined. |
rig. |
The model’s bone names that can be used as overrides. |
The humanoid names cover hips, spine, chest, upperChest, neck, head, jaw, leftEye, rightEye, shoulders (leftShoulder), arms (leftUpperArm, leftLowerArm, leftHand), legs (leftUpperLeg, leftLowerLeg, leftFoot, leftToes) and fingers (leftThumbMetacarpal, leftThumbProximal, leftThumbDistal, leftIndexProximal, leftIndexIntermediate, leftIndexDistal, and the same for Middle, Ring and Little), each also with the right prefix. Partial rigs are valid, such as an upper body without legs. Get the joints again after the model changes.
| Call | Returns |
|---|---|
channels() |
Every channel, in the model’s order. The same array on every call. |
channel(name) |
The channel of the target name, as the model names it, or undefined when no mesh has it. |
hasChannels() |
Whether the loaded model has a morph target. |
A channel has name and value:
- One channel, every mesh. Meshes sharing a target name, such as a face and its teeth, share one channel: setting
valuesets the weight on each of them. - Reading
valuegives the current weight, including what a clip wrote this frame. - Values are usually 0 to 1. Any finite number is accepted; anything else throws a
RangeError. - Clips. A clip’s morph track writes the weight every frame before your
update: a value written inupdatewins that frame.
| Prop | Type | Default | Description |
|---|---|---|---|
weights |
object of name to number | absent | Starting weights by target name, applied when the model loads, before animations start. Targets not listed keep the model’s own weights. Script writes to channels never change weights. |
Examples
Section titled “Examples”1. Sway a head
Section titled “1. Sway a head”The simplest procedural animation: a bone rotated by a sine wave in update.
#pragma lifecycle(update)
const skeleton = self.parent.getComponent(SkeletonComponent);
function update(dt, time) { const head = skeleton.bone('Head'); if (!head) return; // model not loaded yet, or no such bone head.rotation.y = Math.sin(time) * 0.4;}A script turns a character's Head bone with a sine wave every frame, through its Skeleton component.
Watch the head sway from side to side. Drag to orbit the camera, scroll to zoom.
updatereceivestime, the seconds the application has been playing, which makes a smooth oscillation easy.bone('Head')is cheap, so the script calls it every frame instead of caching a bone that a reload would replace.0.4radians is about 23 degrees each way.- Writing every frame means the sway wins over a clip that also animates the head.
2. Look at the player
Section titled “2. Look at the player”A head that turns toward the camera, limited and smoothed, using the humanoid rig so it works on any humanoid model. Set the Skeleton’s rig to { type: 'humanoid' }.
#pragma lifecycle(update)
const MAX_TURN = DEG_TO_RAD(60);const skeleton = self.parent.getComponent(SkeletonComponent);const target = new THREE.Vector3();let yaw = 0; // our own state, not read back from the bone
function update(dt) { const head = skeleton.rig?.bone('head') ?? skeleton.bone('Head'); if (!head || !camera) return;
// Where is the camera, seen from the character? camera.getWorldPosition(target); self.parent.worldToLocal(target); const wanted = THREE.MathUtils.clamp(Math.atan2(target.x, target.z), -MAX_TURN, MAX_TURN);
// Ease toward it, independent of frame rate. yaw += (wanted - yaw) * Math.min(1, dt * 6); head.rotation.y = yaw;}A character's head turns toward the camera through the humanoid rig, limited to 60 degrees each way and eased so it never snaps.
Drag to orbit the camera around the character: her head follows you, up to 60 degrees each way. Scroll to zoom.
skeleton.rig?.bone('head')finds the head by its humanoid name; the??falls back to a bone namedHeadwhen no rig is set.worldToLocalturns the camera’s world position into the character’s own space, soatan2(x, z)is the angle to turn, whichever way the character faces.clampkeeps the head within 60 degrees each side, so it never turns unnaturally far.- The smoothing reads and writes its own
yawvariable. Readinghead.rotation.yback would give the clip’s value for this frame, and the smoothing would never settle.
3. Raise an arm with a limb chain
Section titled “3. Raise an arm with a limb chain”rig.chain returns an arm’s three joints, so a script can pose a whole limb by role. This one raises the right arm while R is held, over whatever clip is playing.
#pragma lifecycle(update)
const skeleton = self.parent.getComponent(SkeletonComponent);let amount = 0;
function update(dt) { const arm = skeleton.rig?.chain('rightArm'); if (!arm) return; const [upper, lower] = arm;
const wanted = Input.keyboard.isKeyPressed(Key.R) ? 1 : 0; amount += (wanted - amount) * Math.min(1, dt * 8); if (amount < 0.001) return; // let the clip pose the arm
upper.rotation.z = -amount * 1.4; lower.rotation.z = -amount * 0.6;}While R is held, a script eases the right arm's upper and lower joints up, found by role with the humanoid rig's chain.
Click the scene, then hold R to raise the right arm and release it to lower it. Drag to orbit the camera, scroll to zoom.
- The chain is
[upper, lower, end]: here the upper arm and forearm. amounteases between 0 and 1, so the arm rises and lowers smoothly.- When
amountis near 0 the script writes nothing, so a playing clip poses the arm as usual. - The rotation axes and signs depend on the rig; adjust them for your model, as with the head.
4. Turn a head and move a mouth
Section titled “4. Turn a head and move a mouth”A Skeleton and a Morph on the same character: the script turns the Head bone, opens and closes the mouth with the mouthOpen target, and eases in a smile while S is held.
#pragma lifecycle(update)
const skeleton = self.parent.getComponent(SkeletonComponent);const face = self.parent.getComponent(MorphComponent);let reported = false;let smile = 0;
function update(dt, time) { const head = skeleton.bone('Head'); const mouth = face.channel('mouthOpen'); const grin = face.channel('mouthSmile'); if (!head || !mouth || !grin) return; // the model is still loading
if (!reported) { reported = true; log(skeleton.bones().length, 'bones. Morph targets:', face.channels().map((c) => c.name).join(', ')); }
head.rotation.y = Math.sin(time) * 0.4; // turn the head side to side mouth.value = (Math.sin(time * 9) + 1) * 0.2; // talk
const wanted = Input.keyboard.isKeyPressed(Key.S) ? 1 : 0; smile += (wanted - smile) * Math.min(1, dt * 8); grin.value = smile;}A script turns a character's Head bone with a sine wave through its Skeleton and drives its mouthOpen and mouthSmile morph targets through its Morph component.
Watch the head turn and the mouth talk. Click the scene and hold S to smile. Drag to orbit the camera, scroll to zoom.
bone()andchannel()returnundefineduntil the model has loaded, so one check covers the loading time.- The first frame they exist, the script logs the bone count and the morph target names, which is the quickest way to learn a new model’s names.
- Each mouth target is shared by the meshes that have it, so the face and teeth move together.
- The smile eases toward its target with
dt, as in Blink and talk with morph targets.
Snippets
Section titled “Snippets”1. Blink and talk with morph targets
Section titled “1. Blink and talk with morph targets”A face with eyesClosed and jawOpen targets blinks every few seconds and opens its mouth while a talk signal says it is speaking.
#pragma lifecycle(startup, update)
const face = self.parent.getComponent(MorphComponent);let mouthTarget = 0;let blink = 0;
function scheduleBlink() { delay(() => { blink = 1; scheduleBlink(); }, Random.range(2000, 5000));}
function startup() { on('talk', (speaking) => { mouthTarget = speaking ? 0.8 : 0; }); scheduleBlink();}
function update(dt) { const jaw = face.channel('jawOpen'); const eyes = face.channel('eyesClosed'); if (!jaw || !eyes) return;
jaw.value += (mouthTarget - jaw.value) * Math.min(1, dt * 12);
eyes.value = blink; blink = Math.max(0, blink - dt * 8); // eyes reopen in about 0.12 s}on('talk', …)receives the data sent with the signal: another script callsemit('talk', true)when speech starts andemit('talk', false)when it ends.delayrunsscheduleBlink’s callback after a random 2 to 5 seconds, then schedules the next one. Pending delays are cancelled automatically when the script stops.- The jaw eases toward its target each frame, so the mouth opens and closes smoothly instead of snapping.
- A blink sets
blinkto 1 (eyes closed) and lets it fall back to 0 over a few frames.
Common mistakes
Section titled “Common mistakes”- Posing once and expecting it to stay. A clip on that bone overwrites it next frame. Write the pose in
update, every frame. - Smoothing from the bone’s own value. Under a clip, the bone’s rotation is the clip’s value each frame. Keep the smoothed value in your own variable.
- Keeping bones or channels across reloads. A model reload makes new ones. Call
bone()andchannel()when you need them; they are cheap. - Bone names from the modelling tool not found. A glTF renames bones (
Tail.001becomesTail001).bone()accepts both, but other names, such as a typo or a different case, returnundefined. Logskeleton.bones().map((b) => b.name)once to see them. - A
rigthat returns nothing.skeleton.rigexists only when therigprop is set and the model is loaded. - Morph values out of range. A non-finite value, such as
NaNfrom a division by zero, throws aRangeError.