Stage 8 of 11
Standing and walking on physics
By the end
robots/robot.gdon Leela's body. She stands on her feet, and with one box ticked in the running game, WASD glides her about.- The four kinds of force that do it: legs that carry, feet that push, a torque that holds her up, and steps that keep a foot under her.
Her bones don't move yet, so she glides like a statue. That's stage 9.
This is the heart of the project: one script, robots/robot.gd, on Leela's body.
The idea
Most game characters are moved by code. A script sets where the character is, or how fast it's going, and a walk clip is played on top to make that look like walking.
Leela is the other way round. She's a rigid body: a thing with weight that the physics engine moves, and that only forces can move. Nobody ever sets her position. Each tick of the physics, her script works out four kinds of force and hands them to the engine:
- Her legs carry her. Each foot on the ground pushes up at its hip, like a spring.
- Her feet push her along, towards the speed she's steered to, as hard as their grip allows.
- A torque keeps her upright. This is the one honest cheat, and the script calls it "the magic".
- Her feet step, one at a time, so there's always a foot under her to do 1 and 2.
Why go to the trouble? Because everything after that is free. She leans when she speeds up and rocks when she stops. Walk her into something and she's stopped by it. Take a leg off and her weight shifts and she hops. Walk her off a ledge and she falls. None of that needs a special animation, because it's all the same body under the same forces.
Why it's like this
The owner pointed to Embark's ARC Raiders, whose machines are physically simulated and learn to walk by reinforcement learning, with some helping forces. This controller is written by hand instead, and its "magic" is its helping force.
Here's one tick, top to bottom. Each line is a part of this stage:
- Read the body: where it is, how fast it's going, which way it faces.
- Steering: the speed she wants.
- Read the ground under her.
- Feet: move the one that's stepping, and start a step if one's needed.
- Legs: each planted foot pushes up at its hip.
- Feet push her towards the speed she wants, within their grip.
- The magic: a torque for upright, leaning and turning.
Put the script on her
- Create
robots/robot.gd. It's long (about a thousand lines), and most of it is special cases that this stage only names. Paste it whole. - Open
leela.tscnand dragrobot.gdontoLeela. - With
Leelaselected, set Look toleela.tres(drag it in from the FileSystem dock). Nothing uses it until stage 9. Leave Part Masses empty until stage 10.
Checkpoint
Run it. She's still a white statue, but she no longer sinks: she drops the 5 cm onto her feet and stands, soles on the floor. (Measured: on her feet in 0.2 s, each leg carrying 147 N, which is half of 30 kg × 9.8.)
- She still sinks: the script isn't on
Leela. - An error about
$Modelor$Shape: those two nodes aren't named exactly that.
She can't be steered yet. First, how she's standing.
Where the forces go: _integrate_forces
A RigidBody3D has a function of its own for this, which the engine calls once every physics tick (60 times a second, unless you've changed it). It hands you state: the body's position and speeds to read, and the place to apply forces.
func _integrate_forces(state: PhysicsDirectBodyState3D) -> void:
var dt := state.step
var xf := state.transform
var v := state.linear_velocity
var w := state.angular_velocity
var space := state.get_space_state()
var com := xf.origin + state.center_of_mass
var yaw := _yaw_of(xf.basis)
var heading := Basis(Vector3.UP, yaw)
_base = Vector3(com.x, xf.origin.y, com.z) # (under its centre of mass, so it doesn't sway as it rolls)xfis where she is and how she's turned.vis her speed,whow fast she's turning.comis her centre of mass in the world.yawis the way she faces._baseis the point under her centre of mass at the height of her feet. Everything about where her feet belong is measured from there.
What a foot is
There's no foot node, and the physics engine knows nothing about feet. A foot is a small record in the script, the class Foot:
| Field | What it holds |
|---|---|
hip | Where the leg joins her body, in her own space. |
spot | Where its ankle stands when she's at rest, in her own space. |
reach | Hip to ankle with the leg straight. |
at | Where the ankle is now, in the world. |
planted | True on the ground, false mid-step. |
t, from, to | How far through its step it is (0 to 1), and where from and to. |
load | The newtons it's carrying. |
A planted foot's at doesn't change. That's what "planted" means: the body moves, and the foot stays where it was put.
All of it is read off the model's skeleton at the start, from the bones' rest positions:
for side in ["L", "R"]:
var foot := Foot.new()
foot.hip = to_me * sk.get_bone_global_rest(sk.find_bone("UpperLeg." + side)).origin
foot.spot = to_me * sk.get_bone_global_rest(sk.find_bone("FootBack." + side)).origin
foot.home_spot = foot.spot
for bone in ["MidLeg.", "LowerLeg.", "FootBack."]:
foot.reach += sk.get_bone_rest(sk.find_bone(bone + side)).origin.length()
foot.reach *= to_me.basis.get_scale().x
feet.append(foot)
feet[0].other = feet[1]
feet[1].other = feet[0]
_ankle = feet[0].spot.y
_height = feet[0].hip.y - feet[0].spot.yFor Leela that comes to hips 0.55 m up and 0.19 m out to each side, ankles 0.02 m up, and a reach of 0.99 m.
One phrase comes up again and again below: a foot's place. It's where its ankle would stand if she were at rest right where she is now, facing the way she's facing: _base + heading * foot.spot.
Legs as springs: _carry()
First, which legs can carry: the ones that are planted and within reach of their hip.
var wb := TAU * (JUMP_BOUNCE if jumping else bounce)
var carrying: Array[Foot] = []
for foot in feet:
foot.load = 0.0
if not foot.gone and foot.planted and (xf * foot.hip).distance_to(foot.at) <= foot.reach:
carrying.append(foot) # (past its reach a leg can't carry)
var carried := 0.0
var side := xf.basis.x.normalized()
var rest := _terrain + _ankle + _heightwbis the spring's frequency turned into the form the sums want.bounceis in Hz, likefin stage 4, and this is the same spring and damper.restis how high her hips should be: the ground's height, plus the ankle's height, plus the hip's height above the ankle. (_terrainis the ground under her. On the flat floor it's 0; stage 11 comes back to it.)
Then the push itself, for each carrying leg:
var inward := 1.0 if legs == 1 else 0.5
for foot in carrying:
var hip := xf * foot.hip
var rising := (v + w.cross(hip - com)).y
var share := mass / carrying.size()
foot.load = clampf(share * (g + wb * wb * (rest - hip.y) - 2.0 * bounce_damping * wb * (rising - rate)), 0.0, most)
var under := hip - side * (hip - com).dot(side) * inward
state.apply_force(Vector3.UP * foot.load, under - xf.origin)
carried += foot.load
return carriedThe long line is the whole idea, so take it apart:
load = share * ( g + wb*wb * (rest - hip.y) - 2 * bounce_damping * wb * rising )
share * gis that leg's share of her weight. With her hips exactly atrestand still, the other two terms are zero, and her legs push up exactly as hard as gravity pulls down. She hovers at standing height.wb*wb * (rest - hip.y)is the spring. Hips too low: push harder. Too high: push less.- 2 * bounce_damping * wb * risingis the damper.risingis how fast the hip is going up, and the push eases off as it does. Without it she'd bob for ever.clampf(..., 0.0, most): never less than nothing. A leg can push; it can't pull her down.underis where the push is applied: at the hip, moved halfway in towards her middle, the way a walker shifts its weight over the standing foot.
(g is 9.8, rate is zero and most is a ceiling of twice her weight, except through a jump. The lines left out keep a leg from being asked to stretch past its reach or fold flat.)
Try it: take the damper out
A change you make in the Remote tree comes too late to see her land, so make this one in the saved scene:
- In
main.tscnselectLeelaand set Bounce Damping to 0.1. Run it. - Watch her feet as she lands. Measured: she dips 3.6 cm and bobs up and down for more than a second, where before she simply arrived.
- Set Bounce to 1 as well: a slow, deep bob that takes three or four seconds to die away.
- Put both back: the small arrow beside a changed property returns it to the scene's own value.
The collider, built in code
One job in _ready() is the collider. The scene's cylinder is the part you edit. The script carries it on downwards:
var holder := $Shape as CollisionShape3D
if holder and holder.shape is CylinderShape3D:
_bottom = holder.position.y - holder.shape.height * 0.5 - TIP.y
_shape_at = holder.transform
_probe = _bevelled(holder.shape, 0.92)
holder.shape = _bevelled(holder.shape, 1.0) ________________
| | the scene's cylinder: radius 0.4, from 0.33 m up to 1.0 m
| |
| |
\ / BEVEL: the rim cut away, 0.12 m up the side
\____ ____/ KNEES: a ring of radius 0.24, 0.30 m up
\__/ TIP: radius 0.05, 0.19 m up
(nothing below that but her legs)
---------------------------- floor
static func _bevelled(cylinder: CylinderShape3D, narrow: float) -> ConvexPolygonShape3D:
var points := PackedVector3Array()
var half := cylinder.height * 0.5
for i in 16:
var rim := Vector3(cos(TAU * i / 16.0), 0.0, sin(TAU * i / 16.0)) * narrow
points.append(rim * cylinder.radius + Vector3.UP * half)
points.append(rim * cylinder.radius + Vector3.UP * (BEVEL - half))
points.append(rim * minf(KNEES.x, cylinder.radius) + Vector3.DOWN * (half + KNEES.y))
points.append(rim * minf(TIP.x, cylinder.radius) + Vector3.DOWN * (half + TIP.y))
var shape := ConvexPolygonShape3D.new()
shape.points = points
return shapeWhy this is code
A convex shape is a list of points, and these 64 points follow from the cylinder's size and three small numbers. Typed into the Inspector by hand they'd be 64 chances to slip, and they'd all be wrong again the day you resized the cylinder. In code, the cylinder stays the thing you edit and the rest follows it.
Why this shape
Each part answers something the owner saw go wrong:
- Down round the knees, because the body passed over anything lower than 0.33 m with her knees going straight through it.
- Sloped underneath, 30° or steeper, so that on an edge she slides off. A flatter one caught on the platform's edge in a fall and left her hanging there, legs dangling.
- Stopping 0.19 m short of the ground, because her crouch and her landings sink 0.15 m.
Steering: the speed she wants
# the speed it's steered to: where the stick or WASD points, as the camera sees it
var stick := Input.get_vector("move_left", "move_right", "move_forward", "move_back") if controlled else Vector2.ZERO
var camera := get_viewport().get_camera_3d()
var turn := (camera.global_rotation.y if camera else 0.0) + _veer
var way := Vector3(stick.x, 0.0, stick.y).rotated(Vector3.UP, turn)
# ...
var legs := feet.filter(func(foot: Foot) -> bool: return not foot.gone)
var want := way * ([crawl_speed, hop_speed, max_speed][legs.size()] as float)
if way.length() > 0.1:
_face = atan2(-way.x, -way.z)stickis the four actions from stage 1 as one direction, and only if she'scontrolled.wayis that direction turned by the camera's yaw, so W always goes up the screen however the camera's turned. (_veeris zero unless she's lost her head.)wantis the speed she's steered to:wayatmax_speed. (The list picks a slower speed when she's lost a leg or both.)_faceis the direction she'll turn to face.
controlled is set by another script, which arrives in stage 10. Until then you tick it by hand.
Feet that push
var speed_up := (want - _flat(v)) * push
# ...
var carried := _carry(state, xf, v, w, com, legs.size())
# its feet push it towards that speed, as hard as their grip allows (low down, as feet do)
state.apply_force((speed_up * mass).limit_length(grip * carried), com - xf.origin + Vector3.DOWN * 0.3)speed_upis the acceleration she'd like: the gap between the speed she wants and the speed she has, timespush. A bigger gap means a harder push, and as she nears the speed she wants, the push fades. (_flat()drops the up-and-down part of a vector.)speed_up * massis the force that gives that acceleration..limit_length(grip * carried)is friction. A foot can't push sideways harder than some part of how hard it's pressing down.carriedis what her legs are carrying this tick, so with no foot down it's nothing, and in the air she simply coasts.Vector3.DOWN * 0.3: the push goes in 0.3 m below her centre of mass, low down, as feet push. That tips her backwards as she sets off, just as it does you. The next part deals with it.
Checkpoint
Run it, press Remote, open Main and then Robots, and click Leela. The Inspector fills with her live values. Its first section is Members, and the first thing in it is Controlled: tick it. Click the game so it has the keyboard, and hold W.
She glides up the screen like a statue on a trolley: legs stiff, but upright, tipping a few degrees as she sets off and as she stops. Measured: 1.76 m/s at full speed, half of that within 0.17 s, and after you let go she's still in 0.7 s, 0.35 m further on.
Her feet are stepping, 15 times in the first two and a half seconds. You can't see it because nothing has told her bones. That's stage 9.
- She doesn't move: Controlled isn't ticked (it's unticked again at every run), or the game hasn't got the keyboard, or the four actions in the input map aren't named exactly as in stage 1.
- She goes the wrong way for the key: the actions' keys are swapped.
Main, Robots, Leela; Controlled is ticked under Members; a click gives the game the keyboard and W walks her. Then Filter Properties finds Grip, it's set to 0.2, and she slides. (The game's view is small here, 406 rows, and at that height the look's pixels are single screen pixels. In a 720-row window they're 2 across.)Try it
With Controlled ticked, change these on Leela in the Remote tree. Her exported values are a long way down the Inspector, below Members and Constants, so type the property's name into Filter Properties at the top.
| Property | From | Try | What happens (measured) |
|---|---|---|---|
| Grip | 0.9 | 0.2 | Ice. 0.9 m in the first second where it was 1.4, and she slides 0.8 m after you let go. |
| Push | 5 | 1 | Sluggish. 0.6 m in the first second, and she coasts 1.3 m after you let go. |
| Max Speed | 1.8 | 3 | 2.9 m/s. |
The magic: upright, leaning, turning
Nothing so far stops her falling over. A real walker stays up by where it puts its feet, which is hard: it's what Embark trained their machines to do. Leela is simply held up, by a torque that no foot or motor could really make.
# the magic: upright, leaning into the speeding up, and turning the way it's going
var up := xf.basis.y
var want_up := (Vector3.UP + speed_up.limit_length(5.0) * lean).normalized()
var axis := up.cross(want_up)
var tilt := Vector3.ZERO
if axis.length() > 0.000001:
tilt = axis.normalized() * acos(clampf(up.dot(want_up), -1.0, 1.0))
var wu := TAU * upright
var wt := TAU * turning
var spin := w.dot(up)
# (the righting part capped, so it gets up off the floor rather than flinging itself up)
var alpha := (tilt * wu * wu).limit_length(60.0) - (w - up * spin) * 2.0 * upright_damping * wu
alpha += up * (angle_difference(yaw, _face) * wt * wt - spin * 2.0 * turn_damping * wt)
state.apply_torque(state.inverse_inertia_tensor.inverse() * alpha)This is stage 4's spring and damper again, turning her this time.
upis her own up.want_upis the up she should have: straight up, tipped a little towardsspeed_up. That tip is the lean: she leans into speeding up, and back as she brakes.tiltis the turn that would takeuptowant_up: an axis to turn about, as long as the angle to turn.alphais the angular acceleration asked for.tilt * wu * wuis the spring towards upright, with a ceiling of 60 so that from flat on the floor she gets up and doesn't fling herself up. The part after the minus is the damper, on her tumbling.- The second
alphaline does the same about her own up axis: a spring that turns her to_face, and a damper on her spin. apply_torque(...): a torque is a turning force, and torque = inertia × angular acceleration, as force = mass × acceleration. The odd-lookinginverse()of an inverse is only how you get her inertia in the world's axes from whatstateoffers.
Why it's like this
The owner tried the honest way for a day: balance by catch steps, an upright torque only through planted feet, falling over past 55° and getting up again. It reacted more, but standing was much harder, and the owner preferred this feel. So it went back.
Try it
In the Remote tree again:
| Property | From | Try | What happens (measured) |
|---|---|---|---|
| Upright | 3.5 | 1 | She leans 14° just standing, and sways up to 20° walking. |
| Upright | 3.5 | 0.5 | She topples right over. Set it back to 3.5 and she's on her feet again in about a second and a half. |
| Upright Damping | 1 | 0.15 | She rocks as she sets off and stops: 7° and 8° where it was 4° and 3°. |
| Lean | 0.03 | 0.12 | She throws herself into setting off: 12° where it was 4°. |
Why does she lean at all with Upright low, standing still? Her legs push up at her hips, and her hips are a few centimetres behind her centre of mass. That small, steady twist is always there. At 3.5 the torque holds it to under a degree.
Steps: when a foot steps
Only planted feet within reach carry her and push her. So as she moves off, her feet have to keep up, or she'd leave them behind and drop. That's all a step is for.
A foot wants to step when it's far from its place. _steps() scores each planted foot and picks the one that needs it most:
var next: Foot = null
var need := 1.0
for foot in feet:
if foot.gone or not foot.planted:
continue
var place := _base + heading * foot.spot
var off := _flat(foot.at - place).length()
# ...
var turned := absf(angle_difference(foot.yaw, yaw)) / twist
var n := maxf(off / stride, turned)
# ...
var other = foot.other
if not other.gone:
if not other.planted:
continue # one foot at a time
# ...
if n > need:
# ...
need = n
next = foot
if next == null:
return false
next.planted = false
next.t = 0.0
next.from = next.at
next.to = next.at
next.from_yaw = next.yaw
return next.other.goneoffis how far the foot is from its place.nis its need to step:offmeasured instrides, or how far she's turned away from the foot measured intwists, whichever is more.needstarts at 1.0. So nothing steps until some foot is a wholestride(0.14 m) from its place or a wholetwist(0.6 rad) off. The neediest foot becomesnext.- One foot at a time: a foot is passed over while the other is in the air.
- The last lines start the step: it's no longer planted,
tis 0, and it remembers where it set off from.
The lines left out are the special cases: a leg nearly out of reach must step whatever its score; once she's been still for a third of a second her feet shuffle back under her; and a step is skipped if it couldn't land any nearer its place.
Steps: how the foot moves
The first half of _steps() moves a foot that's in the air:
for foot in feet:
if foot.gone or foot.planted:
continue
foot.t = minf(foot.t + dt / time, 1.0)
# where its place will be when it lands, half a step on, and further if it's too fast
var ahead := v * time * (1.5 - foot.t) + (v - want) * catch_up
var top := maxf(foot.from.y, _terrain + _ankle) + STEP_UP
var lowest := (xf * foot.hip).y - foot.reach * 0.9
var land := _room(space, foot, _base + heading * foot.spot + ahead, top, heading, lowest)
if is_nan(land.x):
land = foot.from # (a ledge too high, a wall or a drop: it comes back down where it was)
if foot.t > 0.5 and absf(land.y - foot.to.y) > 0.05:
land = foot.to # (past halfway it's set on the ground it's going to)
foot.to = land
var k := smoothstep(0.0, 1.0, foot.t)
# (up onto a step it rises early, and down off one it drops late, clear of the edge)
var rise := smoothstep(0.0, 0.6, foot.t) if land.y > foot.from.y else smoothstep(0.4, 1.0, foot.t)
foot.up = sin(PI * foot.t) * lift * lerpf(1.0, 1.3, quick)
var across := foot.from.lerp(land, k)
foot.at = Vector3(across.x, lerpf(foot.from.y, land.y, rise) + foot.up, across.z)
foot.yaw = lerp_angle(foot.from_yaw, yaw, k)
if foot.t >= 1.0:
foot.planted = true
foot.up = 0.0
foot.slope = _slope(space, foot.at)foot.truns from 0 to 1 overtime, the length of a step:step_time(0.22 s) at a stroll, down to 0.7 of that at full speed.landis where it's going to come down, worked out afresh every tick (next part). The twoifs after it are for uneven ground: with nowhere to land, it comes back down where it was, and past halfway it keeps the ground it's already heading for.keases it across fromfromtoland: slow, fast, slow.risedoes the same for its height when the landing is higher or lower than the start.foot.uplifts it:sin(PI * foot.t)is 0 at the start, 1 in the middle and 0 at the end, so the foot rises toliftand comes down again.- At
t= 1 it's planted where it landed.
Steps: where the foot lands
This is the line that carries the idea:
# where its place will be when it lands, half a step on, and further if it's too fast
var ahead := v * time * (1.5 - foot.t) + (v - want) * catch_upIt's Raibert's rule. Marc Raibert built hopping and running robots in the 1980s, and his answer to "where do I put the foot?" has been used ever since:
Put the foot where the body will be halfway through the time the foot is on the ground. If the body's going faster than you want, put it further ahead still.
A foot put there spends the first half of its time on the ground ahead of the body and the second half behind it. The two halves cancel, and the body keeps its speed. Further ahead, and the foot is in front for longer, which slows the body. Not so far, and it speeds up.
The line says the same in three parts:
v * time * (1 - foot.t): how far she'll travel in what's left of this step. That's where the foot's place will have got to by the time it lands.v * time * 0.5: half a step more. (The two together are the1.5 - foot.t.)(v - want) * catch_up: further still for every m/s she's going faster than she wants.
Be clear about what the rule does here, though. In Raibert's machines it's all there is: where the foot lands is what balances them. Leela is balanced by the magic, and her feet's push doesn't depend on where they stand. For her the rule does two humbler things. Her feet land where a balancing walker's would, so the walk reads as real: out in front when she's stopping, short when she's setting off. And they stay in reach, which the physics does need.
Why it's like this
stride, step_time and max_speed fit each other. At full speed a step takes 0.15 s, and in that time she travels 0.27 m: twice stride. So a foot lands 0.14 m ahead of its place, is 0.14 m behind it one step later, and steps again. Left, right, with never a pause and never both feet up.
Steps: is there ground there?
land isn't just that point. _room() looks for ground near it with room for the whole foot, and the ray under it all is this:
func _ground(space: PhysicsDirectSpaceState3D, at: Vector3, top: float) -> Vector3:
var from := Vector3(at.x, top, at.z)
var query := PhysicsRayQueryParameters3D.create(from, Vector3(at.x, minf(at.y, top) - 1.5, at.z), 1)
query.hit_from_inside = true
var hit := space.intersect_ray(query)
if hit.is_empty():
return at
if hit.normal == Vector3.ZERO:
return Vector3(NAN, NAN, NAN)
return Vector3(at.x, hit.position.y + _ankle, at.z)It looks straight down from top and answers with where an ankle would stand. The last argument to create() is the mask: 1, the level's layer and nothing else. Her feet see the floor and the level's pieces. They don't see other robots or loose parts.
hit_from_inside lets the ray report that it started inside something (a hit with no normal), which means there's a ledge here too high to step onto. That returns NAN, "not a number", which is this script's way of saying "nowhere".
The rest of the script
Everything above is the core: about 250 of the script's thousand lines. The rest is cases, and here's what each is for.
| What | Functions | In a sentence |
|---|---|---|
| Jumping | jump(), _read_jump(), _sample(), _spring(), _fly(), _land() | It follows the model's own Jump clip: stage 11. |
| The ground ahead | _read_ground(), _lowest_here() | Rays read the ground under and ahead of her, so she rises to a step before she reaches it: stage 11. |
| Room for a foot | _room(), _clear(), _slope(), _place_on() | A landing spot is moved clear of walls, edges and her other foot, or the step is called off: stage 11. |
| Edges | _over_drop(), _fall() | Leant out past her feet over a drop, she lets go and falls: stage 11. |
| Walls | _along_walls(), _on_body() | Up against a wall she drops the part of want that points into it, so she doesn't lean or step into it. |
| The mouse's point | _unhandled_input(), _find_target() | A ray from the mouse finds the point on the level her head looks at (stage 9). |
| Losing parts | lose(), regain(), _settle_feet(), _drag(), _lie_down(), head_turned(), _get_up(), _stand_when_clear(), _kick() | Only named in this tutorial: see What's only named. |
| Chasing | _chase() | The same. |
Checkpoint: before stage 9
robot.gdis onLeelainleela.tscn, with Look set toleela.tresand Part Masses empty.- In
main.tscn, Leela's Bounce and Bounce Damping are back at 2.5 and 0.9, with no arrow beside them. - Run it: she drops 5 cm and stands on her soles, white and stiff. With Controlled ticked in the Remote tree, W glides her up the screen.