Secondary Motion: Damped Springs for Hair and Tails
Secondary Motion: Damped Springs for Hair and Tails
Search
Ask the AI

Secondary Motion: Damped Springs for Hair and Tails

Hair, capes, ears, and tails can lag behind the primary action and swing back afterward. This secondary motion gives those parts a different rhythm from the torso. A damped spring is one way to control the response speed and decay.

Secondary motion can be hand-keyed or generated by a physical model as the primary action changes. This article uses a damped spring to explain parameters, integration, bone-length constraints, and pose-solver integration.

One damped spring

Let the current value be x, the target t, and velocity v. The equation below assumes unit mass. For another mass, k and c represent stiffness and damping coefficients divided by that mass:

a = -k · (x - t) - c · v

k controls restoring strength and c controls damping. Raising k while holding c fixed increases the natural frequency and lowers the damping ratio, so the raw coefficients make these motion features harder to tune separately.

Use undamped natural frequency f and damping ratio ζ instead:

omega = 2 * math.pi * f
k = omega * omega
c = 2 * zeta * omega

The frequency f and damping ratio ζ describe time scale and damping regime, but they do not control speed and bounce count independently. For ζ < 1 with ζ ≥ 0, the damped frequency is f√(1−ζ²) and the envelope decays as exp(−ζωτ), where τ is elapsed time. At ζ = 1, the response is critically damped: for a fixed target and an initial displacement released from rest, it is the fastest non-oscillatory response at that natural frequency. Initial velocity or a moving target still requires an overshoot check. The case ζ > 1 is overdamped; this regime alone does not identify the object’s mass.

Ranges of f ∈ [0.5, 6] and ζ ∈ [0.1, 1.2] are possible starting points for sliders. Adjust them for the action, time step, and visual requirements.

Check integration stability against damping and step size

First fix the target and compute acceleration a from the old position and velocity. Explicit Euler updates in this order:

x += v * dt          # position from the OLD velocity
v += a * dt

For an undamped harmonic oscillator, explicit Euler multiplies the norm of the state (x−t, v/ω) by √(1 + ω²dt²) at every step. Any positive step therefore increases energy. Damping can make the method conditionally stable. Let ω > 0, h = dt > 0, ζ ≥ 0, and q = ωh. With a fixed target, asymptotic stability requires 0 < q < 2ζ when 0 < ζ ≤ 1, or 0 < q < 2/(ζ + √(ζ²−1)) when ζ > 1. Increasing k raises ω and changes the allowable step.

Another option updates velocity first, then position using the new velocity. Here a is still computed from the old position and velocity:

v += a * dt          # velocity first
x += v * dt          # position from the NEW velocity

This is velocity-first semi-implicit Euler, also called symplectic Euler in the undamped case. The undamped system is bounded for ω · dt < 2 with ωdt > 0, but does not decay. For the update here, with damping evaluated explicitly, ζ > 0 gives the asymptotic stability condition q² + 4ζq < 4, or 0 < q < 2/(√(1+ζ²)+ζ). At 60 fps with dt ≈ 0.0167, roughly 19 Hz is only the undamped upper bound; at ζ = 1 the bound is about 7.91 Hz. Leave a margin and check accuracy.

These bounds follow from the eigenvalues of the fixed-target update matrices with step dt. Explicit Euler has matrix [[1, q], [−q, 1−2ζq]], while semi-implicit Euler has [[1−q², q(1−2ζq)], [−q, 1−2ζq]]. For the damped system all eigenvalues must have modulus below 1; equality is outside the asymptotically stable region. The MIT numerical analysis notes provide the linear-stability framework for Euler methods; the spring bounds here follow directly from these matrices.

Different frame rates, different results

Even inside the stable region, using each render interval as the integration step changes the discrete trajectory. Amplitude, phase, and decay can differ between 30 fps and 60 fps; the size of the difference depends on the parameters and input motion.

The dependable fix is to pin the physics step and make up the difference with an accumulator:

accumulator += frame_dt
while accumulator >= FIXED_H:          # FIXED_H is typically 1/120
    v += (-k * (x - t) - c * v) * FIXED_H
    x += v * FIXED_H
    accumulator -= FIXED_H

For a prescribed target trajectory, sample it at the physics clock, for example:

steps = 0
while accumulator >= FIXED_H and steps < MAX_STEPS:
    target = sample_target(physics_time)
    v += (-k * (x - target) - c * v) * FIXED_H
    x += v * FIXED_H
    physics_time += FIXED_H
    accumulator -= FIXED_H
    steps += 1

The accumulator separates the integration step from the render rate. Matching trajectories across frame rates also requires sampling the target at the same physical substep times. If the shorthand above holds one t throughout each render frame, a moving target is still sampled differently at different frame rates. Profile the cost of the substeps on the target device.

Cap the steps per render frame so a large frame_dt cannot trigger excessive catch-up work. Normally retain the remainder smaller than one physics step. When the budget is exceeded, define whether to retain backlog, limit incoming time, or drop time. Dropping time changes the simulation clock and trajectory; log frame_dt and backlog to check the policy. Fix Your Timestep! discusses accumulators, budgets, and render interpolation.

Root-to-tip updates for a one-way target chain

Hair and tails are not one spring but a series, and that raises an ordering question, because each segment’s target position is determined by its parent.

In this one-way target chain, reading each parent’s previous-frame result adds one frame of delay at every dependency. Six such cross-frame dependencies add a quarter of a second at 24 fps. That delay comes from the update scheme, not from a general law of spring propagation.

To pass a parent’s current result to its child within the same physics substep, walk the chain root to tip:

for i, seg in enumerate(chain):        # chain is pre-sorted root to tip
    anchor = chain[i - 1].tip if i else root_transform.point
    seg.target = anchor + seg.rest_offset
    seg.step(h)                        # integrate now, for the next segment

This code applies to a chain whose targets depend on parents in one direction. Coupled constraints can instead use iteration or a global solve. Define which substep and iteration supplies each state read by the chosen algorithm.

Angular springs and positional constraints

Springing the bone tip’s position does not automatically preserve bone length. A fixed-length rig needs an angular degree of freedom or a length constraint.

One option is to spring the local angle. Rotation preserves length in a fixed-length chain without additional scale. A limit such as “at most 30 degrees” requires a separate angular constraint; the spring itself does not impose that limit.

Another option integrates positions and then applies a length constraint. The original shorthand below restores rest length only when length(d) ≥ 1e-6:

d = seg.tip - seg.root
seg.tip = seg.root + d / max(length(d), 1e-6) * seg.rest_length

A corrected single-segment example follows. Assume positive rest_length, a valid unit rest_dir, and root velocity root_v in the same space. It removes radial relative velocity after projecting position; coupled chains and collisions still require their solver.

d = seg.tip - seg.root
n = d / length(d) if length(d) >= 1e-6 else seg.rest_dir
seg.tip = seg.root + n * seg.rest_length
relative_v = seg.v - root_v
seg.v = root_v + relative_v - n * dot(relative_v, n)

At d = 0 the original expression leaves the tip at the root; below the threshold it also produces a segment shorter than its rest length. Use a valid rest direction or previous direction in that case. After correcting position, make velocity consistent with the constraint: for a moving root, handle the tip’s radial velocity relative to the root, or reconstruct velocity from the corrected displacement. The algorithm in Position Based Dynamics updates velocity after position projection. The appropriate correction still depends on the constraint and collision solver.

Sometimes you want lag, not a spring

Camera follow, health-bar smoothing, or prop follow may need only a smooth lag. For a step that approaches its current target without overshoot, use a first-order model:

x += (t - x) * (1 - math.exp(-rate * dt))

There is no velocity state. For finite, nonnegative rate and nonnegative dt, the update is a convex combination of the old value and current target, so this step cannot cross that target.

The part to be careful about is that 1 - exp(-rate·dt). The following alternative introduces a frame-rate-dependent bug:

x += (t - x) * 0.1        # wrong: 0.1 is "per frame", not "per second"

Closing 10% of the gap per frame means closing 1 - 0.9^60 ≈ 99.8% in one second at 60 fps, but only 1 - 0.9^30 ≈ 95.8% at 30 fps. With a fixed target, the exponential form is consistent under time subdivision: two steps give the same result in real arithmetic, with a tolerance for floating-point comparisons. A moving target also needs consistent sampling.

A half-life is another useful control in place of rate: “the gap halves every 0.2 seconds.” Require a positive half-life and convert with rate = ln(2) / half_life.

Angle springs have to handle wraparound

Angles can use a periodic interval such as (-180°, 180°], but the difference needs an explicit wrapping convention. From 179° to −179°, the shortest change is 2 degrees, while direct subtraction gives −358 degrees.

The function below maps the difference to [−180°, 180°), choosing −180° for an exact half-turn. Either endpoint convention can work if used consistently. If the simulation uses radians, convert the constants and spring parameters accordingly:

def shortest_delta(a, b):
    d = (b - a + 180.0) % 360.0 - 180.0
    return d

Angle tests should include a crossing of the periodic boundary and an exact 180-degree tie, and verify the selected shortest-path direction.

Order springs and IK by constraint priority

When inverse kinematics and springs share a rig, first decide which constraint has final priority.

For a visual spring overlay, solve IK first and then run the springs. IK executed afterward may rewrite the same joints and overwrite the spring contribution; the effect depends on the controlled joints and blend weights.

The following order treats springs as the final visual overlay:

pose = sample_curves(time)      # keyframes
solve_ik(pose)                  # IK overwrites some joints
step_springs(pose, dt)          # secondary motion layers on the final pose

This order can move the end effector away from its IK target. If foot contact or another constraint must remain exact, reapply it after the spring or solve the constraints together, accepting its restriction on secondary motion. Update affected world matrices after changing the local pose.

Handle target jumps from teleports

The last trap is not in the mathematics; it is in the pipeline.

A teleport or reload may move the target by 2000 pixels in 16 milliseconds. The sudden displacement error creates a large restoring acceleration and subsequent motion; the acceleration equation does not directly estimate target velocity. A camera cut alone need not change a world-space target. A change of reference frame needs its own handling.

If a teleport should return the chain immediately to rest, let the caller explicitly reset its positions and velocities:

def teleport(self, new_root):
    for seg in self.chain:
        seg.x = seg.rest_position_under(new_root)
        seg.v = Vec2(0, 0)

When the caller knows a teleport occurred, send a reset event directly. A displacement threshold can also be a deliberate product policy, but test legitimate high-speed motion to avoid unwanted resets during a sprint.

How to verify it is right

Secondary motion is judged subjectively, but its implementation has several properties you can check objectively.

First, check stability and convergence. Fix the target, disable external forces and projections, select parameters inside the integrator’s stable region, and inspect the long-term trajectory. The continuous damped spring satisfies dE/dτ = −c·v², but discrete semi-implicit Euler need not reduce physical energy at every step. For example, ζ = 0.1 and q = 1.5 are asymptotically stable, yet the state (x−t, v/ω) = (0, 1) gains a factor of 1.5925 in energy after one step. One rising peak or energy value alone does not establish an implementation error; also compare a finer step or an analytic reference.

Second, check the resting fixed point. Starting at a stationary target with zero velocity should preserve rest. Starting from an offset should converge asymptotically only with positive damping and stable parameters; the parameters determine the settling time. Projection, collision, target noise, and velocity updates can all introduce residual jitter and should be checked separately.

Third, compare frame rates at matching physics times. Replay identical input at 30, 60, and 144 fps with the same initial state, physics step, substep target sampling, and time-truncation policy. Align the simulation times before comparing. If differences remain, inspect input sampling, render interpolation, reset timing, and accidental use of frame_dt; a difference alone does not identify its cause.

None of the three requires an art judgement, so all three can be automated and re-run whenever parameters change or the integrator gets refactored.

Leave a Reply

Scroll down