Sonic-style loop-the-loop physics
physicsplatformerloopsmathrail-physics
A rail-based way to let a platformer character run around a full circular loop, staying perpendicular to the track, completing it only with enough speed. Built for Run's level 0. AABB collision cannot do this; the trick is to leave AABB physics entirely while on the loop and integrate an angle instead.
Model
- On entry (a sensor at the bottom of the loop, speed >=
minEntrySpeed) the player "attaches": hitbox set inactive, ground/wall contacts cleared, collision callbacks ignored. - State: angle theta, angular velocity omega, direction, plus a short cooldown (0.3 s) to prevent immediate re-entry after exit.
- Coordinates (screen space, y down): theta = 0 at the bottom, increasing clockwise.
- Position:
(cx + R sin(theta), cy + R cos(theta)) - Tangent for +omega:
(cos(theta), -sin(theta)) - Inward normal:
(-sin(theta), -cos(theta)) - Sprite rotation:
angle = -theta, anchored at the feet (bottom center). - Tangential gravity:
d(omega)/dt = -(g_loop / R) * sin(theta).
Exit conditions
- Jump: exit velocity = tangential velocity + jump impulse along the inward normal.
- Detach (falls off):
v^2 / R + g_loop * cos(theta) < 0, which only happens in the upper half where cos(theta) < 0. - Reversal:
omega * direction <= 0while near the bottom (cos(theta) > 0.5). - Complete:
theta * direction >= 2*pi. On exit, reset the movement state, then set velocityomega * R * tangent(theta).
Tuning math
- Minimum speed at the top:
sqrt(g * R). - Minimum entry speed to complete (energy conservation):
sqrt(5 * g * R). - World gravity (2200 px/s^2) makes loops impossible at game speeds, so loops use their own reduced gravity (default 500). With R = 128 and g = 500: min entry is about 566 px/s, so a sprint (600) barely completes, a run (400) fails, boost + sprint (1080) is easy. Put a boost zone before the loop for comfortable entry.
Design notes
- The loop is terrain-like: it persists across deaths and is not rebuilt like items.
- Timers (boost, invincibility) keep ticking on the loop; speed multipliers affect only entry.
- Guard
radius <= 0(division by zero) and compute an explicit exit velocity; both were real bugs. - Justin's stated requirement for future mechanics: smooth curves, player perpendicular to the surface, speed-dependent completion, reusable configurable components; worth investing in a proper custom physics architecture rather than shortcuts.
See also
- Platformer movement feel (coyote time, jump buffering, wall jumps)
- Fixed-timestep game loop for browser games