TExcelTAD
Home › Game Physics & Animation › Game Physics Exercises

Game Physics Exercises

Time to practise. Each exercise has a starter program that compiles and runs but doesn't do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.

Tip: Physics bugs hide in signs and orders. Before you code, write down which way the normal points, which body gets +j and which -j, and whether you update velocity or position first. Try each exercise for ten minutes before you open the solution.

# Exercise Practises
1 Stop the spring from exploding semi-implicit Euler
2 Write the accumulator fixed timestep, clamping, step cap
3 A collision impulse in one dimension impulses, restitution, inverse mass
4 Stick or slide Coulomb friction, impulse clamping
5 Stop the tunneling swept (continuous) collision
6 Critical damping damped springs
7 Two-bone IK law of cosines, forward kinematics check
8 Sample a looping track keyframes, binary search, wrapping

Exercise 1: Stop the spring from exploding

The spring below should oscillate forever with an energy of about 2.0 J (½·k·x² at the start). It uses explicit Euler, so the energy grows every step. Make it semi-implicit and watch the energy stay bounded.

cpp · try it yourself
#include <iostream>
#include <iomanip>

int main() {
    std::cout << std::fixed << std::setprecision(3);
    const double k = 4, m = 1, dt = 0.05;     // a stiff spring
    double x = 1, v = 0;
    for (int step = 1; step <= 400; step++) {
        // TODO: this is explicit Euler; make it semi-implicit
        double a = -k * x / m;
        x += v * dt;
        v += a * dt;
        if (step % 100 == 0) std::cout << "t=" << step * dt << "  x=" << x << "  energy=" << 0.5 * m * v * v + 0.5 * k * x * x << "\n";
    }
}
t=5.000  x=-1.409  energy=5.410
t=10.000  x=1.265  energy=14.632
t=15.000  x=0.247  energy=39.577
t=20.000  x=-4.116  energy=107.048

Expected output when solved:

text
t=5.000  x=-0.809  energy=1.911
t=10.000  x=0.355  energy=1.935
t=15.000  x=0.216  energy=2.043
t=20.000  x=-0.716  energy=2.105

Hint: Two lines swap places. See Euler, Semi-Implicit Euler and Verlet.

Show solution
cpp
#include <iostream>
#include <iomanip>

int main() {
    std::cout << std::fixed << std::setprecision(3);
    const double k = 4, m = 1, dt = 0.05;
    double x = 1, v = 0;
    for (int step = 1; step <= 400; step++) {
        v += -k * x / m * dt;      // velocity first...
        x += v * dt;               // ...then move with the new velocity
        if (step % 100 == 0) std::cout << "t=" << step * dt << "  x=" << x << "  energy=" << 0.5 * m * v * v + 0.5 * k * x * x << "\n";
    }
}

The energy now wobbles around 2.0 instead of growing; the small wobble is normal for a symplectic integrator.

Exercise 2: Write the accumulator

Physics runs at 50 Hz (20 ms steps). Feed the uneven frame times into an accumulator: clamp each frame to 100 ms, run as many fixed steps as fit but at most 3 per frame, and drop the leftover time when the cap is hit.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <algorithm>

int main() {
    std::cout << std::fixed << std::setprecision(1);
    const double STEP = 20.0;                                   // ms (50 Hz, like Unity's default)
    const double frames[] = {16.7, 16.7, 16.6, 33.3, 8.3, 300.0, 16.7};
    double acc = 0;
    int total = 0;
    for (double f : frames) {
        int steps = 0;
        // TODO: add the frame time to the accumulator, clamped to 100 ms,
        //       then run as many fixed steps as fit, but at most 3 per frame
        //       (if the cap is hit, drop the leftover time)
        (void)STEP;                                             // remove this line when you use STEP
        total += steps;
        std::cout << "frame " << std::setw(5) << f << " ms: " << steps << " steps, accumulator " << acc << " ms\n";
    }
    std::cout << "total steps: " << total << "\n";
}
frame  16.7 ms: 0 steps, accumulator 0.0 ms
frame  16.7 ms: 0 steps, accumulator 0.0 ms
frame  16.6 ms: 0 steps, accumulator 0.0 ms
frame  33.3 ms: 0 steps, accumulator 0.0 ms
frame   8.3 ms: 0 steps, accumulator 0.0 ms
frame 300.0 ms: 0 steps, accumulator 0.0 ms
frame  16.7 ms: 0 steps, accumulator 0.0 ms
total steps: 0

Expected output when solved:

text
frame  16.7 ms: 0 steps, accumulator 16.7 ms
frame  16.7 ms: 1 steps, accumulator 13.4 ms
frame  16.6 ms: 1 steps, accumulator 10.0 ms
frame  33.3 ms: 2 steps, accumulator 3.3 ms
frame   8.3 ms: 0 steps, accumulator 11.6 ms
frame 300.0 ms: 3 steps, accumulator 0.0 ms
frame  16.7 ms: 0 steps, accumulator 16.7 ms
total steps: 7

Hint: acc += min(frame, 100), then while (acc >= STEP && steps < 3). See Fixed Timestep and Interpolation.

Show solution
cpp
#include <iostream>
#include <iomanip>
#include <algorithm>

int main() {
    std::cout << std::fixed << std::setprecision(1);
    const double STEP = 20.0;
    const double frames[] = {16.7, 16.7, 16.6, 33.3, 8.3, 300.0, 16.7};
    double acc = 0;
    int total = 0;
    for (double f : frames) {
        int steps = 0;
        acc += std::min(f, 100.0);
        while (acc >= STEP && steps < 3) { acc -= STEP; steps++; }
        if (steps == 3) acc = 0;
        total += steps;
        std::cout << "frame " << std::setw(5) << f << " ms: " << steps << " steps, accumulator " << acc << " ms\n";
    }
    std::cout << "total steps: " << total << "\n";
}

The 300 ms hitch is clamped to 100 ms, then capped at 3 steps, so the game loses 240 ms of simulated time instead of trying to catch up.

Exercise 3: A collision impulse in one dimension

Implement collisionImpulse for two bodies on a line. An inverse mass of 0 means an immovable wall. Bodies that are already separating must get no impulse.

cpp · try it yourself
#include <iostream>
#include <iomanip>

// Two bodies on a line collide. Return the impulse on body b (body a gets -j).
// e is the restitution (0 = stick, 1 = perfectly elastic). invMass 0 = immovable.
double collisionImpulse(double invMassA, double vA, double invMassB, double vB, double e) {
    // TODO: j = -(1 + e) * vRel / (invMassA + invMassB), with vRel = vB - vA,
    //       and no impulse if the bodies are already separating (vRel >= 0)
    return 0;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    struct Case { const char* name; double imA, vA, imB, vB, e; };
    Case cases[] = {
        {"equal masses, elastic", 1, 2, 1, 0, 1},
        {"equal masses, e = 0.5", 1, 2, 1, 0, 0.5},
        {"ball vs wall, e = 0.8", 1, 3, 0, 0, 0.8},
        {"light vs heavy (1:10)", 1, 2, 0.1, 0, 1},
        {"already separating", 1, -1, 1, 1, 1},
    };
    for (auto& c : cases) {
        double j = collisionImpulse(c.imA, c.vA, c.imB, c.vB, c.e);
        std::cout << c.name << ": vA " << c.vA - j * c.imA << ", vB " << c.vB + j * c.imB << "\n";
    }
}
equal masses, elastic: vA 2.000, vB 0.000
equal masses, e = 0.5: vA 2.000, vB 0.000
ball vs wall, e = 0.8: vA 3.000, vB 0.000
light vs heavy (1:10): vA 2.000, vB 0.000
already separating: vA -1.000, vB 1.000

Expected output when solved:

text
equal masses, elastic: vA 0.000, vB 2.000
equal masses, e = 0.5: vA 0.500, vB 1.500
ball vs wall, e = 0.8: vA -2.400, vB 0.000
light vs heavy (1:10): vA -1.636, vB 0.364
already separating: vA -1.000, vB 1.000

Hint: Only the relative velocity along the normal matters, and the impulse is shared through the inverse masses. See Impulses and Restitution.

Show solution
cpp
#include <iostream>
#include <iomanip>

double collisionImpulse(double invMassA, double vA, double invMassB, double vB, double e) {
    double vRel = vB - vA;
    if (vRel >= 0) return 0;                       // separating: leave them alone
    return -(1 + e) * vRel / (invMassA + invMassB);
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    struct Case { const char* name; double imA, vA, imB, vB, e; };
    Case cases[] = {
        {"equal masses, elastic", 1, 2, 1, 0, 1},
        {"equal masses, e = 0.5", 1, 2, 1, 0, 0.5},
        {"ball vs wall, e = 0.8", 1, 3, 0, 0, 0.8},
        {"light vs heavy (1:10)", 1, 2, 0.1, 0, 1},
        {"already separating", 1, -1, 1, 1, 1},
    };
    for (auto& c : cases) {
        double j = collisionImpulse(c.imA, c.vA, c.imB, c.vB, c.e);
        std::cout << c.name << ": vA " << c.vA - j * c.imA << ", vB " << c.vB + j * c.imB << "\n";
    }
}

Note the 1:10 case: the light body bounces back fast while the heavy one barely moves, and the wall case loses 20% of the speed (e = 0.8).

Exercise 4: Stick or slide

A box rests on slopes of different angles with a friction coefficient of 0.5. Apply a friction impulse each step that tries to cancel the velocity, clamped to μ times the normal impulse. The box should stay put on gentle slopes and slide on steep ones. (The critical angle is atan(0.5), about 26.6°.)

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>

// A 1 kg box starts at rest on a slope. Each step, gravity pulls it along the slope
// and a friction impulse (at most mu * normal impulse) tries to cancel its velocity.
double slideDistance(double slopeDeg, double mu) {
    const double g = 9.81, dt = 1.0 / 60.0, PI = 3.14159265358979;
    double angle = slopeDeg * PI / 180, v = 0, s = 0;
    for (int i = 0; i < 60; i++) {
        v += g * std::sin(angle) * dt;                 // gravity along the slope
        double jn = g * std::cos(angle) * dt;          // normal impulse this step (m = 1)
        // TODO: apply a friction impulse that brings v toward 0,
        //       clamped to the range [-mu * jn, mu * jn]
        (void)jn; (void)mu;
        s += v * dt;
    }
    return s;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    for (double deg : {10.0, 20.0, 26.0, 27.0, 40.0})
        std::cout << "slope " << deg << " deg, mu 0.5: slides " << slideDistance(deg, 0.5) << " m in 1 s\n";
}
slope 10.000 deg, mu 0.5: slides 0.866 m in 1 s
slope 20.000 deg, mu 0.5: slides 1.706 m in 1 s
slope 26.000 deg, mu 0.5: slides 2.186 m in 1 s
slope 27.000 deg, mu 0.5: slides 2.264 m in 1 s
slope 40.000 deg, mu 0.5: slides 3.205 m in 1 s

Expected output when solved:

text
slope 10.000 deg, mu 0.5: slides 0.000 m in 1 s
slope 20.000 deg, mu 0.5: slides 0.000 m in 1 s
slope 26.000 deg, mu 0.5: slides 0.000 m in 1 s
slope 27.000 deg, mu 0.5: slides 0.042 m in 1 s
slope 40.000 deg, mu 0.5: slides 1.295 m in 1 s

Hint: With m = 1 the impulse that stops the box is simply -v. Clamp it with std::clamp. See Friction.

Show solution
cpp
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>

// A 1 kg box starts at rest on a slope. Each step, gravity pulls it along the slope
// and a friction impulse (at most mu * normal impulse) tries to cancel its velocity.
double slideDistance(double slopeDeg, double mu) {
    const double g = 9.81, dt = 1.0 / 60.0, PI = 3.14159265358979;
    double angle = slopeDeg * PI / 180, v = 0, s = 0;
    for (int i = 0; i < 60; i++) {
        v += g * std::sin(angle) * dt;                 // gravity along the slope
        double jn = g * std::cos(angle) * dt;          // normal impulse this step (m = 1)
        double jt = std::clamp(-v, -mu * jn, mu * jn);  // wanted impulse: -v (m = 1), within the Coulomb limit
        v += jt;
        s += v * dt;
    }
    return s;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    for (double deg : {10.0, 20.0, 26.0, 27.0, 40.0})
        std::cout << "slope " << deg << " deg, mu 0.5: slides " << slideDistance(deg, 0.5) << " m in 1 s\n";
}

Below 26.6° the friction impulse always has enough budget to cancel gravity's pull, so the box never moves; at 27° it creeps, at 40° it slides.

Exercise 5: Stop the tunneling

A ball of radius 0.2 flies at a thin wall. The discrete overlap test detects the hit late at medium speeds and misses it completely at 1000 m/s. Replace it with a swept test so every speed stops exactly at the wall's face (x = 4.8 for the ball's center).

cpp · try it yourself
#include <iostream>
#include <iomanip>

// A ball (radius 0.2) flies along +x toward a thin wall occupying 5.0 <= x <= 5.1.
// Return the x where the ball first touches the wall, or -1 if it passes through.
double firstContact(double speed) {
    const double r = 0.2, wallMin = 5.0, wallMax = 5.1, dt = 1.0 / 60.0;
    double x = 0;
    for (int i = 0; i < 600; i++) {
        double next = x + speed * dt;
        // TODO: replace this discrete overlap test with a swept test: if the ball's
        //       front (x + r) crosses wallMin during this step, return the contact x
        if (next + r >= wallMin && next - r <= wallMax) return next;
        x = next;
    }
    return -1;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    for (double speed : {5.0, 20.0, 100.0, 1000.0}) {
        double hit = firstContact(speed);
        if (hit < 0) std::cout << "speed " << speed << ": tunneled through\n";
        else std::cout << "speed " << speed << ": contact at x = " << hit << "\n";
    }
}
speed 5.000: contact at x = 4.833
speed 20.000: contact at x = 5.000
speed 100.000: contact at x = 5.000
speed 1000.000: tunneled through

Expected output when solved:

text
speed 5.000: contact at x = 4.800
speed 20.000: contact at x = 4.800
speed 100.000: contact at x = 4.800
speed 1000.000: contact at x = 4.800

Hint: Test whether the ball's front x + r is before the wall at the start of the step and past it at the end. See Tunneling and Continuous Collision Detection.

Show solution
cpp
#include <iostream>
#include <iomanip>

// A ball (radius 0.2) flies along +x toward a thin wall occupying 5.0 <= x <= 5.1.
// Return the x where the ball first touches the wall, or -1 if it passes through.
double firstContact(double speed) {
    const double r = 0.2, wallMin = 5.0, dt = 1.0 / 60.0;
    double x = 0;
    for (int i = 0; i < 600; i++) {
        double next = x + speed * dt;
        if (x + r <= wallMin && next + r >= wallMin)   // the front crosses the wall's face this step
            return wallMin - r;                          // time of impact -> position at contact
        x = next;
    }
    return -1;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    for (double speed : {5.0, 20.0, 100.0, 1000.0}) {
        double hit = firstContact(speed);
        if (hit < 0) std::cout << "speed " << speed << ": tunneled through\n";
        else std::cout << "speed " << speed << ": contact at x = " << hit << "\n";
    }
}

Every speed now reports the same contact point, the one a perfect continuous simulation would find.

Exercise 6: Critical damping

A spring should settle without overshooting, as fast as possible. Compute the damping coefficient from a damping ratio zeta: zeta = 1 is critical damping.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>

// A 2 kg mass on a spring (k = 50) starts 1 m from rest position.
// Damping c is chosen from the damping ratio zeta: zeta = 1 is critical damping.
double dampingFor(double zeta, double k, double m) {
    // TODO: critical damping is 2 * sqrt(k * m); scale it by zeta
    (void)zeta; (void)k; (void)m;
    return 0;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    const double k = 50, m = 2, dt = 1.0 / 240.0;
    for (double zeta : {0.2, 1.0, 2.0}) {
        double c = dampingFor(zeta, k, m), x = 1, v = 0, minX = 1, settle = -1;
        for (int i = 1; i <= 960; i++) {                    // 4 seconds
            v += (-k * x - c * v) / m * dt;
            x += v * dt;
            minX = std::fmin(minX, x);
            if (settle < 0 && std::fabs(x) < 0.01 && std::fabs(v) < 0.05) settle = i * dt;
        }
        std::cout << "zeta " << zeta << ": c = " << c << ", overshoot " << (minX < 0 ? -minX : 0.0) << " m, ";
        if (settle < 0) std::cout << "still moving after 4 s\n";
        else std::cout << "settles after " << settle << " s\n";
    }
}
zeta 0.200: c = 0.000, overshoot 1.000 m, still moving after 4 s
zeta 1.000: c = 0.000, overshoot 1.000 m, still moving after 4 s
zeta 2.000: c = 0.000, overshoot 1.000 m, still moving after 4 s

Expected output when solved:

text
zeta 0.200: c = 4.000, overshoot 0.526 m, still moving after 4 s
zeta 1.000: c = 20.000, overshoot 0.000 m, settles after 1.346 s
zeta 2.000: c = 40.000, overshoot 0.000 m, settles after 3.500 s

Hint: Critical damping is 2·√(k·m). See Springs and Damping.

Show solution
cpp
#include <iostream>
#include <iomanip>
#include <cmath>

// A 2 kg mass on a spring (k = 50) starts 1 m from rest position.
// Damping c is chosen from the damping ratio zeta: zeta = 1 is critical damping.
double dampingFor(double zeta, double k, double m) {
    return zeta * 2 * std::sqrt(k * m);
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    const double k = 50, m = 2, dt = 1.0 / 240.0;
    for (double zeta : {0.2, 1.0, 2.0}) {
        double c = dampingFor(zeta, k, m), x = 1, v = 0, minX = 1, settle = -1;
        for (int i = 1; i <= 960; i++) {                    // 4 seconds
            v += (-k * x - c * v) / m * dt;
            x += v * dt;
            minX = std::fmin(minX, x);
            if (settle < 0 && std::fabs(x) < 0.01 && std::fabs(v) < 0.05) settle = i * dt;
        }
        std::cout << "zeta " << zeta << ": c = " << c << ", overshoot " << (minX < 0 ? -minX : 0.0) << " m, ";
        if (settle < 0) std::cout << "still moving after 4 s\n";
        else std::cout << "settles after " << settle << " s\n";
    }
}

zeta = 0.2 still bounces, zeta = 1 settles fastest with no overshoot, and zeta = 2 (overdamped) creeps in slowly. Camera springs and UI motion usually want a ratio near 1.

Exercise 7: Two-bone IK

Solve a 2D arm (upper arm 2, forearm 1.5) so the hand reaches each target. The program checks your angles with forward kinematics, so the hand position must equal the target whenever it is reachable, and a target out of reach should straighten the arm toward it.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>

// Two-bone IK in 2D: shoulder at the origin, upper arm L1, forearm L2.
// Find the shoulder angle (from +x) and the elbow bend so the hand reaches the target.
// Bend the elbow so it ends up on the counter-clockwise side of the target line.
void solveIK(double L1, double L2, double tx, double ty, double& shoulder, double& elbow) {
    // TODO: d = distance to target, clamped to the reachable range [|L1 - L2|, L1 + L2]
    //       elbow    = PI - acos((L1² + L2² - d²) / (2·L1·L2))    (0 = straight arm)
    //       shoulder = atan2(ty, tx) + acos((L1² + d² - L2²) / (2·L1·d))
    (void)L1; (void)L2; (void)tx; (void)ty;
    shoulder = 0; elbow = 0;
}

double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }

int main() {
    std::cout << std::fixed << std::setprecision(3);
    const double L1 = 2, L2 = 1.5, PI = 3.14159265358979;
    double targets[][2] = {{3, 1}, {1, 2}, {0, -1}, {5, 0}};
    for (auto& t : targets) {
        double sh, el;
        solveIK(L1, L2, t[0], t[1], sh, el);
        double ex = L1 * std::cos(sh), ey = L1 * std::sin(sh);          // forward kinematics check
        double hx = ex + L2 * std::cos(sh - el), hy = ey + L2 * std::sin(sh - el);
        std::cout << "target (" << t[0] << ", " << t[1] << "): shoulder " << std::setw(8) << z0(sh * 180 / PI)
                  << " deg, elbow " << std::setw(7) << z0(el * 180 / PI) << " deg, hand (" << z0(hx) << ", " << z0(hy) << ")\n";
    }
}
target (3.000, 1.000): shoulder    0.000 deg, elbow   0.000 deg, hand (3.500, 0.000)
target (1.000, 2.000): shoulder    0.000 deg, elbow   0.000 deg, hand (3.500, 0.000)
target (0.000, -1.000): shoulder    0.000 deg, elbow   0.000 deg, hand (3.500, 0.000)
target (5.000, 0.000): shoulder    0.000 deg, elbow   0.000 deg, hand (3.500, 0.000)

Expected output when solved:

text
target (3.000, 1.000): shoulder   40.168 deg, elbow  51.318 deg, hand (3.000, 1.000)
target (1.000, 2.000): shoulder  104.438 deg, elbow 102.025 deg, hand (1.000, 2.000)
target (0.000, -1.000): shoulder  -43.433 deg, elbow 151.045 deg, hand (0.000, -1.000)
target (5.000, 0.000): shoulder    0.000 deg, elbow   0.000 deg, hand (3.500, 0.000)

Hint: Use the law of cosines twice: once for the elbow's inner angle, once for the angle between the shoulder–target line and the upper arm. See Two-Bone IK.

Show solution
cpp
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>

// Two-bone IK in 2D: shoulder at the origin, upper arm L1, forearm L2.
// Find the shoulder angle (from +x) and the elbow bend so the hand reaches the target.
// Bend the elbow so it ends up on the counter-clockwise side of the target line.
void solveIK(double L1, double L2, double tx, double ty, double& shoulder, double& elbow) {
    const double PI = 3.14159265358979;
    double d = std::clamp(std::hypot(tx, ty), std::max(std::fabs(L1 - L2), 1e-9), L1 + L2);   // reachable range
    double cosInner = (L1 * L1 + L2 * L2 - d * d) / (2 * L1 * L2);     // law of cosines at the elbow
    double cosShoulder = (L1 * L1 + d * d - L2 * L2) / (2 * L1 * d);    // and at the shoulder
    elbow = PI - std::acos(std::clamp(cosInner, -1.0, 1.0));
    shoulder = std::atan2(ty, tx) + std::acos(std::clamp(cosShoulder, -1.0, 1.0));
}

double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }

int main() {
    std::cout << std::fixed << std::setprecision(3);
    const double L1 = 2, L2 = 1.5, PI = 3.14159265358979;
    double targets[][2] = {{3, 1}, {1, 2}, {0, -1}, {5, 0}};
    for (auto& t : targets) {
        double sh, el;
        solveIK(L1, L2, t[0], t[1], sh, el);
        double ex = L1 * std::cos(sh), ey = L1 * std::sin(sh);          // forward kinematics check
        double hx = ex + L2 * std::cos(sh - el), hy = ey + L2 * std::sin(sh - el);
        std::cout << "target (" << t[0] << ", " << t[1] << "): shoulder " << std::setw(8) << z0(sh * 180 / PI)
                  << " deg, elbow " << std::setw(7) << z0(el * 180 / PI) << " deg, hand (" << z0(hx) << ", " << z0(hy) << ")\n";
    }
}

The target at (5, 0) is 5 m away but the arm is only 3.5 m long, so the solver clamps the distance and the arm points straight at it.

Exercise 8: Sample a looping track

Implement sampleTrack for a looping track of keys (time, value) with linear interpolation. Times outside the clip, including negative ones, wrap around.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <algorithm>

struct Key { double t, value; };

// Sample a looping animation track with linear interpolation.
// The clip length is the time of the last key; the last key should equal the first.
double sampleTrack(const std::vector<Key>& keys, double t) {
    // TODO: 1. wrap t into [0, length) with fmod (careful: negative t)
    //       2. find the first key with key.t > t (std::upper_bound or a loop)
    //       3. lerp between the key before it and that key
    (void)t;
    return keys[0].value;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    std::vector<Key> doorHeight = {{0.0, 0.0}, {0.5, 2.0}, {1.2, 2.0}, {2.0, 0.0}};   // up, hold, down
    for (double t : {0.0, 0.25, 0.9, 1.6, 2.0, 2.25, 4.1, -0.4})
        std::cout << "t = " << std::setw(6) << t << " -> " << sampleTrack(doorHeight, t) << "\n";
}
t =  0.000 -> 0.000
t =  0.250 -> 0.000
t =  0.900 -> 0.000
t =  1.600 -> 0.000
t =  2.000 -> 0.000
t =  2.250 -> 0.000
t =  4.100 -> 0.000
t = -0.400 -> 0.000

Expected output when solved:

text
t =  0.000 -> 0.000
t =  0.250 -> 1.000
t =  0.900 -> 2.000
t =  1.600 -> 1.000
t =  2.000 -> 0.000
t =  2.250 -> 1.000
t =  4.100 -> 0.400
t = -0.400 -> 1.000

Hint: std::fmod returns a negative result for a negative t; add the clip length in that case. See Keyframes and Sampling.

Show solution
cpp
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <algorithm>

struct Key { double t, value; };

// Sample a looping animation track with linear interpolation.
// The clip length is the time of the last key; the last key should equal the first.
double sampleTrack(const std::vector<Key>& keys, double t) {
    double length = keys.back().t;
    t = std::fmod(t, length);
    if (t < 0) t += length;                                 // fmod keeps the sign of t
    auto next = std::upper_bound(keys.begin(), keys.end(), t, [](double v, const Key& k) { return v < k.t; });
    auto prev = next - 1;                                   // next is never begin(), since keys[0].t == 0 <= t
    double u = (t - prev->t) / (next->t - prev->t);
    return prev->value + (next->value - prev->value) * u;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    std::vector<Key> doorHeight = {{0.0, 0.0}, {0.5, 2.0}, {1.2, 2.0}, {2.0, 0.0}};   // up, hold, down
    for (double t : {0.0, 0.25, 0.9, 1.6, 2.0, 2.25, 4.1, -0.4})
        std::cout << "t = " << std::setw(6) << t << " -> " << sampleTrack(doorHeight, t) << "\n";
}

At t = 4.1 the clip has looped twice and t wraps to 0.1; at t = -0.4 it wraps to 1.6.

Test yourself

In Exercise 2, why is the leftover time dropped when the step cap is reached?

  1. To keep the physics deterministic
  2. Otherwise the next frames would try to catch up and the game would stay slow (spiral of death)
  3. Because the accumulator can't hold more than one step
  4. To save memory

In Exercise 4, why does the box stay still on a 20° slope with μ = 0.5?

  1. Gravity is too weak
  2. The friction impulse needed to cancel gravity's pull is smaller than μ times the normal impulse
  3. The normal impulse is zero
  4. The box is asleep

In Exercise 6, what happens with a damping ratio of 2?

  1. It oscillates forever
  2. It doesn't overshoot but settles more slowly than with critical damping
  3. It explodes
  4. It settles instantly