Stage 9 of 11
Her bones
By the end
robots/rig.gdon aRignode. She has her colours, sways standing still, turns her head to the mouse, and visibly walks.- Inverse kinematics on her three-bone leg, and how her upper body borrows the model's clips in time with her feet.
Leela's body moves, rolls and leans by itself now, and her feet know where they are. This stage makes the picture catch up: robots/rig.gd sets her bones, every frame.
Put the script on her
- Create
robots/rig.gd. - Open
leela.tscn. Add a Node underLeela(the plain kind, not a Node3D), name itRig, and dragrig.gdonto it.
Its two exported values, Head Spring (2.5, 1, 0) and Walk Speed (0.6), stay as they are.
Checkpoint
Run it.
- She has her colours. The rig puts her material on her mesh.
- She's alive standing still: her upper body sways through the model's Idle clip.
- Her head turns to the mouse, up to 63° either side.
- She walks. In the Remote tree tick Controlled on
Leelaonce more and hold W. Her feet lift, swing and land, her knees bend to reach them, and her body swings in time with her steps.
Measured over a walk: each ankle bone sits on its foot's point to within a tenth of a millimetre.
- Still white: Look isn't set on
Leela(stage 8). - An error naming
"../Model": the model's node isn't calledModel, orRigisn't directly underLeela. - Her legs bend backwards or point the wrong way:
Model's Rotation isn't 0, 180, 0.
Bones, and who sets them
A skinned model's mesh follows its skeleton. Each bone has a pose: where it is and how it's turned, relative to the bone it hangs from. Usually an AnimationPlayer sets the poses, from a clip. Here a script does. No clip is ever played.
func _ready() -> void:
var model := $"../Model"
skeleton = model.find_children("*", "Skeleton3D", true, false)[0]
mesh = skeleton.find_children("*", "MeshInstance3D", false, false)[0]
if _robot.look:
mesh.material_override = _robot.look
var player: AnimationPlayer = model.find_children("*", "AnimationPlayer", true, false)[0]
player.active = false # (psx.gd leaves switched-off players alone)mesh.material_override = _robot.lookis why she's no longer white.player.active = falseswitches the AnimationPlayer off for good. Its clips are still there to be read: "what's this bone's rotation 0.3 s into Walk?" is a question you can ask a clip without playing it.
The rest of _ready() gets things ready for that: the pose to start each frame from, which track of each clip turns which bone, and which bones are leg bones.
Every frame, _process() puts every bone back to that starting pose:
for bone in sk.get_bone_count():
sk.set_bone_pose_rotation(bone, _pose_rot[bone])
sk.set_bone_pose_position(bone, _pose_pos[bone])Then it poses her upper body from the clips, turns her head, and bends each leg to its foot. In the order she's easiest to understand: legs first.
Legs: inverse kinematics
Stage 8 gave each foot a point in the world, foot.at. The leg has to get from the hip to that point.
Posing a leg the ordinary way is forward kinematics: you choose each joint's angle, and where the foot ends up follows. Inverse kinematics, IK, is the other way round: you say where the foot must be, and work out the angles that put it there.
Her leg has three bones in a zig-zag:
hip o
\
\ a UpperLeg: down and forwards
\
o knee
/
/ b MidLeg: down and back
/
o hock
\
\ c LowerLeg: parallel to the first
\
o ankle
Three bones can reach a point in endlessly many ways, so the script adds a rule taken from the model's rest pose: the first and last bones stay parallel. Then a neat thing happens. Going from hip to ankle you travel a along one direction, b along another, and c along the first again. Do the two parallel parts first and it's a + c one way, then b. That's a triangle:
hip o
|\
| \
| \ a + c the first and last bones, end to end
d | \
| o
| /
| / b the middle bone
| /
ankle o
You know all three sides: a + c, b, and d, the distance from hip to ankle. The law of cosines gives a triangle's angles from its sides. For the angle A at the hip:
cos A = ( (a + c)^2 + d^2 - b^2 ) / ( 2 * (a + c) * d )
func _reach(leg: Leg, foot, to_skel: Transform3D) -> void:
var sk := skeleton
var hip := sk.get_bone_global_pose(leg.bones[0]).origin
var reach: Vector3 = to_skel * foot.at - hip
var long := leg.a + leg.c
var d := clampf(reach.length(), absf(long - leg.b) + 0.001, long + leg.b - 0.001)
var along := reach.normalized()
var ahead := (FORWARD - along * FORWARD.dot(along)).normalized() # square to `along`, towards its front
var cos_a := clampf((long * long + d * d - leg.b * leg.b) / (2.0 * long * d), -1.0, 1.0)
var u := along * cos_a + ahead * sqrt(1.0 - cos_a * cos_a) # the first and last bones
var v := (along * d - u * long).normalized() # the middle one
var bend := along.cross(ahead)
var parent := sk.get_bone_global_pose(sk.get_bone_parent(leg.bones[0])).basis
var dirs := [u, v, u]
for i in 3:
var x: Vector3 = bend * leg.signs[i]
var y: Vector3 = dirs[i]
var global := Basis(x, y, x.cross(y))
sk.set_bone_pose_rotation(leg.bones[i], (parent.inverse() * global).get_rotation_quaternion())
parent = globalreachis the line from hip to ankle, in the skeleton's own space.dis its length, held between the shortest and longest the leg can be.aheadis square to that line, towards her front.cos_ais the law of cosines.uis the direction of the first and last bones: the hip-to-ankle line swung forwards by the angle A. Forwards is what puts her knees in front.vis the middle bone's direction: whatever's left to get to the ankle.- The loop turns each of the three bones to its direction. A bone points along its own y, and its x is the axis the leg bends about.
The lengths come from the skeleton, in its own units: 1.45, 1.68 and 1.82. The model is scaled by 0.2, so that's 0.29, 0.34 and 0.36 m, and together the 0.99 m of reach from stage 8.
Feet
A foot shouldn't tilt just because the leg above it leans. The end of _reach() sets it level in the world:
# the foot: flat on the ground whichever way it leans (along its slope, when it's planted on one),
# turned its own way, toes down mid-step
var world := Basis(Vector3.UP, foot.yaw + PI) # (the model is turned round inside the robot)
leg.slope = leg.slope.lerp(foot.slope if foot.planted else Vector3.UP, _slope_ease).normalized()
world = Basis(Quaternion(Vector3.UP, leg.slope)) * world
if not foot.planted and not _robot.airborne:
var front := Vector3(-sin(foot.yaw), 0.0, -cos(foot.yaw))
world = Basis(front.cross(Vector3.DOWN).normalized(), sin(PI * foot.t) * TOE_DOWN) * world
var to_bones := sk.global_basis.orthonormalized().inverse() * world
sk.set_bone_pose_rotation(leg.bones[3], (parent.inverse() * to_bones * leg.heel).get_rotation_quaternion())
sk.set_bone_pose_position(leg.bones[4], sk.get_bone_global_pose(leg.bones[3]).origin)
sk.set_bone_pose_rotation(leg.bones[4], (to_bones * leg.toes).get_rotation_quaternion())worldstarts as the way the foot faces, level.leg.slopetips it to lie along the ground it's planted on. In the air it's level.- Mid-step its toes dip:
sin(PI * foot.t)is the same rise and fall that lifts the foot in stage 8. - The last three lines turn the heel bone, then move the bone that carries her sole and toes to the ankle and turn it the same way.
Why it's like this
Both were seen going wrong first. Level feet dug 2 to 3 cm into the ramp. And the sole's bone, Foot.L or Foot.R, hangs from nothing: left alone, her soles stayed on the ground while her legs stepped away.
Try it: her steps
Now you can see what stage 8 described. With Controlled ticked, change these on Leela in the Remote tree, and walk. They're in her Steps group, a long way down the Inspector: Filter Properties finds each by name.
| Property | From | Try | What happens |
|---|---|---|---|
| Stride | 0.14 | 0.3 | Fewer, longer steps: 12 in two and a half seconds where there were 15. Each foot trails further before it goes. |
| Step Time | 0.22 | 0.45 | Slow feet: 8 steps in the same time. |
| Lift | 0.09 | 0.25 | A high-stepping march. (Read from the code, not measured.) |
Her upper body, from the model's own clips
Her legs are worked out. Everything else (hips, torso, chest, neck, head) borrows its pose from the model's clips: Idle while she stands, Walk as she gets going, Jump through a jump.
Why it's like this
The first version moved her upper body with springs. The owner found it too springy, and asked for the clips.
The clever part is the clock. Idle just plays by time. Walk doesn't:
for i in 2:
var foot = _robot.feet[i]
if not foot.gone and not foot.planted and not _robot.airborne:
# this step is the half of Walk from where this foot lifts
var span := fposmod(_lifts[1 - i] - _lifts[i], walk.length)
if span < 0.01:
span = walk.length * 0.5
_walk_time = fposmod(_lifts[i] + foot.t * span, walk.length)_liftsholds the moment each foot lifts off in the Walk clip, found at the start by looking at the clip's foot heights. For Leela: 0.07 s for the left foot and 0.60 s for the right, in a clip 1.04 s long.spanis the time from this foot's lift to the other's: half the cycle._walk_timeis where to read Walk: this foot's lift, plusfoot.tof that half.
So a step is half of Walk's cycle. As her foot goes from lifting to landing, the clip goes from that foot's lift to the other's. Quick steps play it quickly. Stop mid-stride and it stops. Her body can never swing out of time with her feet, because her feet are the clock.
Then the three clips are blended, one bone at a time:
var k := 1.0 - exp(-delta / SMOOTH)
for bone in _upper:
var q := _pose_rot[bone]
if _tracks.Idle.has(bone):
q = idle.rotation_track_interpolate(_tracks.Idle[bone], _idle_time)
if _walk_weight > 0.0 and _tracks.Walk.has(bone):
q = q.slerp(walk.rotation_track_interpolate(_tracks.Walk[bone], _walk_time), _walk_weight)
if _jump_weight > 0.0 and _tracks.Jump.has(bone):
q = q.slerp(jump.rotation_track_interpolate(_tracks.Jump[bone], _jump_time), _jump_weight)
_now[bone] = _now[bone].slerp(q, k)
skeleton.set_bone_pose_rotation(bone, _now[bone])qstarts as Idle's rotation for this bone.slerpblends two rotations._walk_weightgoes from 0 to 1 as her speed goes from nothing towalk_speed, so Walk takes over as she gets going. Jump is laid over both._now[bone].slerp(q, k): the bone doesn't jump toq. It eases there (SMOOTH, 0.06 s), so a sudden change of clip never snaps her pose.
Only the clips' rotations are read. A clip can't move her hips about: the physics does that.
Her head
Stage 4 again:
func _look(delta: float, to_skel: Transform3D) -> void:
var pose := skeleton.get_bone_global_pose(_head)
var aim := Vector2.ZERO # how far round and up from its front
var target: Vector3 = _robot.target
var away := target - _robot.global_position
if Vector2(away.x, away.z).length() > 0.4:
var at := to_skel * (target + Vector3.UP * 0.6) - pose.origin
aim.x = clampf(atan2(at.x, at.z), -1.1, 1.1)
aim.y = clampf(atan2(at.y, Vector2(at.x, at.z).length()), -0.5, 0.35)
_head_follow.set_parameters(head_spring.x, head_spring.y, head_spring.z)
var a: Vector2 = _head_follow.update(delta, aim)
_set_global_basis(_head, Basis.from_euler(Vector3(-a.y, a.x, 0.0)) * pose.basis)aimis how far round and how far up the mouse's point is from her front, each held within limits: 1.1 rad (63°) to either side. If the point is nearly under her, she looks straight ahead._head_followis aSecondOrderon those two angles.- The last line turns the head bone by what comes out.
Try it
No steering needed. In the Remote tree open Leela, click Rig and change Head Spring (Filter Properties finds it). Its three numbers are f, z and r. Then flick the mouse from one side of her to the other.
| Head Spring | What her head does (measured) |
|---|---|
| 2.5, 1, 0 | The project's values: there in 0.4 s, no overshoot. |
| 2.5, 0.25, 0 | Swings almost half as far again past the point, and wobbles to rest. A bobble-head. |
| 0.8, 1, 0 | Slow and heavy: well over a second. |
| 2.5, 1, 2 | Snaps a quarter too far, then settles back. |
Why it's like this
Letting her head turn all the way round was added at the owner's ask and taken out again at theirs.
Checkpoint: before stage 10
Rigis a plain Node directly underLeelainleela.tscn, withrig.gdon it.- The game is stopped, so Head Spring is 2.5, 1, 0 again and her steps have their own numbers.
- Run it: she has her colours, her head follows the mouse, and with Controlled ticked she walks on bending legs.