Rollball · physics model 6
Building the hamster ball, one layer at a time
A clear plastic sphere, a heavy hamster hanging inside it, and a motor between the two. This is how Rollball's ball is built from first principles: two bodies, closed-form maths, and a check against the shipped game's numbers after every layer. The Try it panels let you turn the terms yourself; each shows one term on its own, not the whole ball.
Why a pendulum in a sphere
There are three classic ways to drive a ball from the inside. You can put a cart on wheels inside the shell, balance a body on top of the ball like a ballbot, or hang a heavy body below the centre on a gimbal and put a motor between the body and the shell. Rollball uses the last one.
When the motor pushes the shell forward, the reaction swings the hamster forward and up the inside of the ball. Gravity pulls that offset weight back down, and that pull is what holds the drive torque. Lean further and the ball accelerates harder; lean back and it brakes; lean sideways and it turns. The hanging body is passively stable, it responds the moment the motor turns, and its lean is the actuator state, so the game draws exactly what the physics is doing.
The cart version is physically the same pendulum with extra wheel slip, so it's a fine way to draw the ball but adds nothing to simulate. The ballbot must roll backwards before it can go forwards and falls over without fast control. A kinematic arcade ball with a decorative hamster has no coupling, so slopes, slides and drifts never emerge from it. A full 3D multibody solver would need iteration counts that depend on the data, and ghosts and replays need a fixed cost and bit-identical results.
The rest of this article builds the model in the order you would implement it. Each layer ends with a checkpoint: a scenario, the value the shipped model v4 measures, and the requirement it satisfies in the redesign spec. Model 6 doesn't have to match v4 bit for bit, only within those tolerances, and that freedom is what lets it fix v4's defects along the way.
Layer 01
Ground rules: one step, the same bits everywhere
Rollball records every run as a ghost: one input per step. Replaying a ghost, or checking a leaderboard time on the server, means running the simulation again. That only works if the simulation is a pure function of its state and its input, and gives the same bits on a Mac, a Windows PC and a browser.
So there are rules before there is any physics. The game always steps at 1/120 s. All memory lives in one plain, trivially copyable struct of 34 floats, a material id and some flags. Arithmetic is float32 only, compiled with fused multiply-add turned off, because a compiler that fuses a*b + c on one platform and not another changes the last bit. Trigonometry comes from a small deterministic library built from + − × ÷ and sqrt, which IEEE 754 rounds identically everywhere; libm's sin doesn't. Colliders and contacts are visited in a documented order, and decaying values are flushed to zero before they go subnormal.
Physics happens in a contact frame rebuilt every substep: the normal \(n\) from the ground to the ball's centre, the forward tangent \(t_1\) (the heading projected onto the ground), and \(t_2 = t_1 \times n\) to the right. Almost everything below is done once per tangent axis.
Layer 02
A rolling ball weighs more than it is
Take the shell on its own. A block sliding down a slope accelerates at \(g\sin\varphi\). A rolling ball is slower, because some of gravity's work goes into spinning the shell. The trick that keeps everything else simple: while the ball rolls without slipping, its surface speed \(u\) and its centre's speed \(v\) are locked together. The shell's rotational inertia then behaves exactly like extra mass, \(I' = I_s / R^2\). For a thin shell \(I_s = \tfrac23 m_s R^2\), so \(I' = \tfrac23 m_s = 0.08\) with the shell's 0.12 of mass.
The shell is light (10% of the mass), so the rolling mass \(\tilde M\) is only 1.28 against a real mass of 1.2. The ball rolls downhill at \(0.9375\, g \sin\varphi\). Most of the mass is the hamster, which doesn't spin with the shell.
The state advances by semi-implicit Euler: velocities first, then positions from the new velocities. It is cheap and keeps oscillators from slowly gaining energy. The orientation integrates the angular velocity exactly as a quaternion rotation. Rolling resistance is a load-proportional deceleration applied as a scale that can never reverse the motion. Drag is an exact exponential decay, so it doesn't depend on how many substeps the step is split into.
Layer 03
The hamster inside
Now hang the body. On one tangent axis there are three coordinates: the centre's displacement \(s\), the shell's rolling angle (surface speed \(u\)), and the body's climb angle \(\theta\), measured from hanging straight down. The body's centre of mass sits \(\ell = 0.63\) m below the ball's centre and carries 90% of the mass.
Writing the kinetic and potential energy and applying Euler–Lagrange gives three equations per axis, with \(a_0 = m_b\ell = 0.680\) the body's static moment and \(J = m_b(\ell^2 + r_g^2) = 0.526\) its inertia about the centre. While the shell grips, \(\ddot s = \dot u\) and friction can be eliminated, leaving a 2×2 system solved in closed form:
The friction this needs is \(F = M\,(\text{centre-of-mass acceleration} - g_t)\), the only tangential external force. The next layer checks it against what the ground can give.
The one design rule
Solve that system at rest for a torque step. The ball goes forwards straight away only if the body's mass is spread out enough:
With a radius of gyration \(r_g = 0.3\) m, \(r_g^2 = 0.09\) against a threshold of 0.044: about twice the threshold. A compact hamster would roll the ball backwards first every time you hit the throttle, like a ballbot. The forward and right axes are solved as two independent planar pendulums. They couple only through the shared friction, the shared load and the tilt budget. The cross-axis terms this ignores cost under 10% even with both axes leaning hard, and only change the shape of the wobble.
Layer 04
Friction: stick until you can't
The simulation doesn't integrate forces. It solves for velocities over each substep, so friction is an impulse. First the free response: what the shell, the centre and the body would do in one substep with no friction at all. Then the stick impulse is the impulse that would make the shell's surface speed match the centre's exactly. It is a closed-form scalar per axis.
The two axes' stick impulses form one vector, and the ground can only give so much: \(\mu_s\Lambda\), static friction times the normal impulse. If the vector fits inside that circle the ball rolls. If it doesn't, traction breaks, and the impulse is clamped to the smaller kinetic circle \(\mu_k\Lambda\) with \(\mu_k = 0.7\,\mu_s\), in the stick impulse's direction. A sliding shell regrips when the stick impulse fits inside the kinetic circle again, or when the slip speed falls below 0.5 m/s and it fits inside the static circle. The gap between the two circles is the hysteresis that makes slides hold and then let go cleanly.
One more limit keeps a spinning shell sane: the slip between shell and centre is capped at 6 m/s, fading to 0.5 m/s as the load drops below 0.3 g over a crest, where there is almost no friction to stop it.
Layer 05
Standing up: the balance loop
The motor is the only actuator, so something has to decide its torque. The balance loop holds the body at a target tilt. It is a PD controller on the tilt error, made exact by feedback linearisation: the torque is computed from the equations of layer 03 so that the closed loop behaves like a perfect second-order system, whatever the slope or the coupling.
The bandwidth scales with the square root of the load for the same reason the passive pendulum's frequency does, so the ball feels equally crisp in a 3 g banked turn. Discretised at 1/120 s the loop's eigenvalues have magnitude 0.906. A cap keeps \(\omega h\) below 80% of the discrete stability bound if someone tunes it hard. A friction-aware limiter scales the swing transient so the heavy body never breaks grip on its own. The torque saturates at 60 N·m times the load factor, and an end stop at 75° means the body can never flip.
Layer 06
Asking for acceleration
Hold the body at a fixed lean and the ball settles to a fixed acceleration. Setting the rates to zero in layer 03's system gives it in closed form:
On flat ground it rises steeply, peaks at \(\theta^* = 40.6°\) and then falls. Past the peak, more lean gives less acceleration, which is positive feedback towards swinging over the top. So the lean is capped at \(\theta_{max} = 38°\), just short of it. That gives the ball a natural, smooth top end of authority at about 29 m/s².
Steady acceleration against body lean, flat ground, 1 g
Computed from the stick model at v4's defaults
Show as a table
| Lean | 5° | 10° | 15° | 20° | 25° | 30° | 38° | 40.6° |
|---|---|---|---|---|---|---|---|---|
| a (m/s²) | 6.8 | 13.1 | 18.4 | 22.7 | 25.7 | 27.7 | 29.1 | 29.2 |
The controller needs the inverse: the lean that produces a desired acceleration. The relation is linear in \(\cos\theta\) and \(\sin\theta\), so it solves with one square root and one atan2, taking the hanging branch. v4 learned one subtlety the hard way: if the request is beyond the slope's authority, clamp the request to what ±38° can give before solving. Clamping the solution instead returns less lean the more you ask for. The two axes share a tilt budget, lateral first, so steering never loses to throttle.
Layer 07
The command layer
Above the tilt targets sits a small layer that turns stick and pedal into requested accelerations, one per axis:
- Throttle. 18 m/s² up to 14 m/s, then a linear taper to nothing at 24 m/s. Above top speed nothing drives the ball; gravity can still carry it past.
- Brake. 0.76 × the load \(g_n\), scaled by the surface's grip, \(\gamma = \min\big(1,\ \mu_s / (1.4\,\mu_{scale})\big)\), which works out to the surface friction over 1.4. The brake then asks for the same share of the friction circle on ice as on the road. It fades out near standstill.
- Park. Below 0.4 m/s with no throttle, the ball holds an anchor point: gravity along the slope is fed forward and a spring corrects the rest. Model 6 lets go once the ball is pushed and keeps moving.
- Reverse. Brake held 0.3 s while parked reverses at up to 8 m/s. Model 6 also ends it when the ball leaves the ground (v4 didn't).
- The grip budget. On its own the ball never asks for more than 95% of static friction, lateral first, so it never breaks traction by itself. The brake is exempt. That exemption is the drift.
v4 switched the exemption on at brake > 0: any touch of the brake removed the grip limit on both axes, throttle included. With an analog trigger, a feathered brake plus full throttle on ice gave wheelspin. Model 6 blends the exemption in over a small brake range (a brake share, proposed full at 0.1), and the exemption only ever covers the brake and steering demands: the throttle always stays inside the budget. The analog brake behaves continuously and the drift's numbers stay the same.
Layer 08
Steering and the drift
Steering doesn't push the ball sideways. It turns the heading, the direction the hamster faces, and a lateral demand then drags the velocity round after it, like tyres. The smoothed steer \(\delta\) and the yaw rate \(r\) are positive to the right, towards \(t_2\), and \(v_1, v_2\) are the velocity's forward and rightward parts:
At low speed full steer turns at a fixed 2.4 rad/s, so the ball turns on the spot; rolling backwards faster than 1 m/s the steering mirrors, blending in between. Above 7.9 m/s it asks for a fixed sideways acceleration, 0.76 g, so the radius grows as \(v^2\) and steering feels the same at 10 m/s and at 300 m/s. Only the geometry changes. The steer slews at 5/s and returns at 8/s, so a 0.1 s keyboard tap at 20 m/s turns the heading about 2.2°.
A drift that isn't scripted
Brake hard and steer: the two requests together exceed the friction circle and traction breaks. Two terms then keep the slide controllable. The yaw rate is boosted by 1.3× so the heading leads into the turn, and an alignment term \(1.5\,\beta\) pulls it back towards the velocity, so the slip angle settles instead of growing. A clamp at 40° rules out spin-outs. Let go of the steer and the alignment term swings the heading back onto the velocity; once the stick impulse fits the kinetic circle again, the shell regrips.
Slip angle in a brake-and-steer drift from 22 m/s
v4, measured every 0.1 s; shaded while the shell slides; steer released at 1.25 s
Show as a table
| t (s) | sliding | slip (°) | speed (m/s) | lean (°) |
|---|
v4 switched these terms with hard gates at 1 m/s and mirrored the steering at −1 m/s, a 2.4 rad/s jump in yaw rate at full steer. Model 6 blends every gate over a range. It also rotates the heading by exactly \(rh\) each substep, where v4 rotated by \(\arctan(rh)\), which depended slightly on the substep count.
Layer 09
Meeting the world
So far the ground was a perfect plane. Real levels are boxes, track pieces, ramps and walls. Once per step the sim asks the world for the colliders near the ball: a deterministic query with no silent cap, because v4's quiet limit of 64 could drop the ground itself. Then, up to four times per substep, it queries each one for a contact point, a normal, a depth, a surface velocity and a material.
Contacts are speculative. Each collider is queried 5 cm further out than the ball's surface, and a ball within that skin counts as grounded. That stops ground contact flickering over seams and at rest. Inside the skin the ball may approach at the gap's speed, so it touches down smoothly instead of being stopped early.
A contact whose normal points within 75° of up is ground; anything steeper is a wall, which scrapes with kinetic friction. Contacts are resolved one after another, by default in ascending collider order. That order is part of the model, so it is written down rather than left to chance.
Layer 10
Load and many contacts
With several contacts at once, the sim merges them into one support: one normal (weighted by impulse), one ground velocity and the material of the strongest contact. The ball's load, the apparent gravity \(g_n\) that scales grip, steering, brake and the balance loop, comes from the impulses. Which sum matters. Two faces of a V-crease each push at an angle. Their scalar sum says 1.155 g, but the body only feels their vector sum, 1.00 g. So the body and the controller use the vector sum, while friction uses the scalar sum, because both faces really grip. The load is filtered over 30 ms then clamped to 20 g, so impacts reach the body as friction wobble rather than as one substep of enormous gravity.
Moving platforms come for free: a contact's ground velocity is the platform's surface velocity, and the frame is relative to it, so a platform carries the ball through grip, and an icy one slides away underneath.
Layer 11
Shaped ground
Levels are built from pieces, and pieces have edges. A handful of rules make them drive like continuous ground:
- Curbs. A box edge up to 0.21 m high is reported as the top face through a virtual chamfer of slope 0.4, so the ball climbs onto it as ground. Its speed pays for the height as gravity would, spin included. Above that it blends into a hard edge over 0.14 m.
- Seams. Edges and end faces buried in a neighbouring piece give no contact, so flush tiles don't jolt the ball.
- Rollers. Authored bumps in a track bed change a contact's depth and tilt its normal by the height field's gradient. A speed gain flattens them above their design speed, keeping crests under 0.5 g and vertical speed under 1.5 m/s.
- Lips. On 30–50° ground while climbing, the ball stops holding its line and rolls freely sideways, and the heading follows. Without this, a ball coasting into a lip at an angle corkscrewed up and over the rim.
- Walls. After a graze the heading turns with the deflected velocity, so a scrape doesn't keep steering the ball into the wall: 91% of the speed is kept after a 15° graze.
- Crests. Below 0.3 g the lean targets fade to upright and wheelspin is held to 0.5 m/s, so a weightless ball doesn't spin up its shell.
Layer 12
In the air
With no contact there is no normal, so the frame uses a reference normal: the last ground normal, slewed towards world up at 2 rad/s. The lean targets go upright, the load decays to zero and is flushed, and the steer yaws the heading at 1.5 rad/s so the player can line up a landing. Because the body's lean is measured relative to that normal, it can't "flip" on landing. Touching down clears parking. A landing at an angle to the heading starts a slide that regrips in a fraction of a second.
Layer 13
Substeps and stability
At 300 m/s the ball travels 2.5 m in one step, more than three times its radius: far enough to miss a thin piece or skip the 5 cm skin on a curve. So each step is split into \(k\) equal substeps, the fewest that keep each one's travel under 0.35 R:
k is chosen once from the state at the start of the step, so it is as deterministic as everything else. Then nothing else may depend on it beyond integration error. Model 6 uses exact rotations and exact exponential filters, so four substeps of h filter exactly as one of 4h, and turn and damp the same to within integration error. In v4 the per-substep forms \(h/(h+\tau)\) and \(\arctan(rh)\) made results drift slightly with speed.
Layer 14
The step, assembled
Put the layers in the order of the figure and you have the whole simulation, a few hundred lines with no model gates. Assembly adds three safety rails v4 lacked:
- Sanitised input. Throttle and brake are clamped to 0..1, steer to −1..1, and NaN reads as 0. v4 clamped only the steer, so a negative throttle drove backwards and blocked parking.
- A NaN guard. If a step ever produces a non-finite value, the state rolls back to the start of the step with its velocities zeroed and a counter ticks. Both platforms take the same branch because the check reads deterministic values.
- Validated parameters. Every tunable, including the thresholds v4 hard-coded, lives in one parameter struct with a validator, so no slider position can produce a division by zero.
Layer 15
Plugging it into the game
The game reaches the ball through one wrapper, BallSim, which now dispatches on the physics model number, so models 1–5 keep replaying their old ghosts unchanged. Model 6 has to honour what the rest of the game already assumes:
- Drawing. The body's two lean angles are published in the frame the renderer uses to place the drive unit inside the shell, and the ground normal is the reference normal.
- Ghosts. The input format is unchanged. The tuning hash lists model 6's parameters field by field instead of hashing the struct's raw bytes, which in v4 meant that reordering one field silently invalidated every stored ghost.
- Bots. Bots plan with the ball's numbers: full steer as 0.76 g sideways up to 2.4 rad/s, brake as 0.76 g, top speed 24 m/s. Their limit on brake² + steer² is now derived from model 6's measured drift onset. v4's bots stayed under 1.15, assuming a static friction circle that predicts the drift at 1.22. Measured from 20 m/s at full brake, it really starts at about 1.09, because the lean's swing adds to the demand while the turn builds.
- Audio and haptics. A per-substep export with the slip, load, torque, wall contacts and events is output only: the state's hash is the same with it on or off.
Layer 16
Proving it
Every checkpoint above becomes a C++ test with a tolerance rather than a pinned hash. A band in the spec is the tolerance, a count of zero must be exactly zero, a loss is compared as a loss, and anything else gets ±10%. A few are tighter: top speed to 0.1 m/s, lateral acceleration to 3%, braking distance to 5%. Bit-exact fingerprints come only once model 6 freezes, and then native and WebAssembly must match. Last comes the content: medals regenerated within ±10% of v4's, every challenge re-solved, every race level finished by the bots.
| Feel | v4 measures | Model 6 must hit |
|---|---|---|
| 0 → 20 m/s | 1.36 s | ±10% |
| Braking 20 → 0 m/s | 12.0 m | ±5% |
| Full-steer radius at 20 m/s | 21.7 m | ±10% |
| Drift onset at 22 m/s | 0.18 s | < 0.25 s |
| 6 m drop rebound | 0.29 m | < 0.35 m, one bounce |
| 1.39 m slot | holds | holds |
| Rollers at 8–70 m/s | never airborne | 0 airborne steps |
| Replay across platforms | bit-identical | bit-identical |
When a test fails, the layer order says where to look. The checkpoints were built bottom-up, so the lowest failing one names the layer to bisect.