TExcelTAD
Home › Math for Games › Math for Games Exercises

Math for Games 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: Draw the situation on paper first: two dots and an arrow are often enough to see which vector to subtract from which. Try each exercise for ten minutes before you open the solution.

# Exercise Practises
1 Chase at constant speed subtraction, length, normalize
2 Vision cone dot product, cosine threshold
3 Bouncing in a box reflection
4 Turret angles atan2, degrees
5 Local and world rotation + translation and its inverse
6 Quaternion turns axis-angle quaternions, composition
7 Fix the follow camera frame-rate-independent damping
8 Click to select ray–sphere, closest hit

Exercise 1: Chase at constant speed

The enemy should move toward the player at exactly 2 units per second (dt = 0.5), and stop on the player instead of overshooting. The starter adds the raw arrow to the player, so the enemy jumps there instantly.

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

struct Vec2 { double x, y; };
Vec2 operator+(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
Vec2 operator*(Vec2 v, double s) { return {v.x * s, v.y * s}; }
double length(Vec2 v) { return std::sqrt(v.x * v.x + v.y * v.y); }

int main() {
    std::cout << std::fixed << std::setprecision(3);
    Vec2 enemy{0, 0}, player{3, 4};
    const double speed = 2, dt = 0.5;
    for (int step = 1; step <= 6; step++) {
        Vec2 toPlayer = player - enemy;
        // TODO: move by at most speed * dt along the normalized direction,
        //       and never past the player
        enemy = enemy + toPlayer;
        std::cout << "step " << step << ": (" << enemy.x << ", " << enemy.y << ")\n";
    }
}
step 1: (3.000, 4.000)
step 2: (3.000, 4.000)
step 3: (3.000, 4.000)
step 4: (3.000, 4.000)
step 5: (3.000, 4.000)
step 6: (3.000, 4.000)

Expected output when solved:

text
step 1: (0.600, 0.800)
step 2: (1.200, 1.600)
step 3: (1.800, 2.400)
step 4: (2.400, 3.200)
step 5: (3.000, 4.000)
step 6: (3.000, 4.000)

Hint: Compare length(toPlayer) with speed * dt. If the remaining distance is smaller, snap to the player.

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

struct Vec2 { double x, y; };
Vec2 operator+(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
Vec2 operator*(Vec2 v, double s) { return {v.x * s, v.y * s}; }
double length(Vec2 v) { return std::sqrt(v.x * v.x + v.y * v.y); }

int main() {
    std::cout << std::fixed << std::setprecision(3);
    Vec2 enemy{0, 0}, player{3, 4};
    const double speed = 2, dt = 0.5;
    for (int step = 1; step <= 6; step++) {
        Vec2 toPlayer = player - enemy;
        double dist = length(toPlayer), maxStep = speed * dt;
        if (dist <= maxStep) enemy = player;
        else enemy = enemy + toPlayer * (maxStep / dist);
        std::cout << "step " << step << ": (" << enemy.x << ", " << enemy.y << ")\n";
    }
}

Exercise 2: Vision cone

canSee should return true when the target is within range and inside a cone of fovDegrees around facing (a unit vector). Use a dot product and a cosine, not acos.

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

struct Vec2 { double x, y; };
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }

bool canSee(Vec2 eye, Vec2 facing, double fovDegrees, double range, Vec2 target) {
    // TODO: range check, then compare dot(facing, normalized direction) with cos(fov / 2)
    return false;
}

int main() {
    std::cout << std::boolalpha;
    Vec2 eye{0, 0}, facing{1, 0};
    Vec2 targets[] = {{5, 1}, {5, 4}, {2, -1}, {-3, 0}, {12, 0}};
    for (Vec2 t : targets)
        std::cout << "(" << t.x << ", " << t.y << "): " << canSee(eye, facing, 60, 10, t) << "\n";
}
(5, 1): false
(5, 4): false
(2, -1): false
(-3, 0): false
(12, 0): false

Expected output when solved:

text
(5, 1): true
(5, 4): false
(2, -1): true
(-3, 0): false
(12, 0): false

Hint: A 60° cone extends 30° to each side, so the threshold is cos(30°) ≈ 0.866.

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

struct Vec2 { double x, y; };
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }

bool canSee(Vec2 eye, Vec2 facing, double fovDegrees, double range, Vec2 target) {
    Vec2 to = target - eye;
    double dist = std::sqrt(dot(to, to));
    if (dist > range) return false;
    if (dist < 1e-9) return true;
    double cosHalf = std::cos(fovDegrees / 2 * std::numbers::pi / 180);
    return dot(facing, to) / dist >= cosHalf;
}

int main() {
    std::cout << std::boolalpha;
    Vec2 eye{0, 0}, facing{1, 0};
    Vec2 targets[] = {{5, 1}, {5, 4}, {2, -1}, {-3, 0}, {12, 0}};
    for (Vec2 t : targets)
        std::cout << "(" << t.x << ", " << t.y << "): " << canSee(eye, facing, 60, 10, t) << "\n";
}

Exercise 3: Bouncing in a box

A ball moves inside the box 0 <= x <= 10, 0 <= y <= 6. When it leaves the box, put it back on the wall and reflect its velocity with v - 2 * dot(v, n) * n, using the wall's inward normal. The starter lets it fly away.

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

struct Vec2 { double x, y; };
Vec2 operator+(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
Vec2 operator*(Vec2 v, double s) { return {v.x * s, v.y * s}; }
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }

Vec2 reflect(Vec2 v, Vec2 n) { return v - n * (2 * dot(v, n)); }

int main() {
    std::cout << std::fixed << std::setprecision(1);
    Vec2 pos{2, 3}, vel{4, 3};
    const double dt = 0.5;
    for (int step = 1; step <= 8; step++) {
        pos = pos + vel * dt;
        // TODO: for each of the four walls, if pos is outside it:
        //       clamp pos back onto the wall and reflect vel with the wall's inward normal
        std::cout << "step " << step << ": pos (" << pos.x << ", " << pos.y << ") vel (" << vel.x << ", " << vel.y << ")\n";
    }
}
step 1: pos (4.0, 4.5) vel (4.0, 3.0)
step 2: pos (6.0, 6.0) vel (4.0, 3.0)
step 3: pos (8.0, 7.5) vel (4.0, 3.0)
step 4: pos (10.0, 9.0) vel (4.0, 3.0)
step 5: pos (12.0, 10.5) vel (4.0, 3.0)
step 6: pos (14.0, 12.0) vel (4.0, 3.0)
step 7: pos (16.0, 13.5) vel (4.0, 3.0)
step 8: pos (18.0, 15.0) vel (4.0, 3.0)

Expected output when solved:

text
step 1: pos (4.0, 4.5) vel (4.0, 3.0)
step 2: pos (6.0, 6.0) vel (4.0, 3.0)
step 3: pos (8.0, 6.0) vel (4.0, -3.0)
step 4: pos (10.0, 4.5) vel (4.0, -3.0)
step 5: pos (10.0, 3.0) vel (-4.0, -3.0)
step 6: pos (8.0, 1.5) vel (-4.0, -3.0)
step 7: pos (6.0, 0.0) vel (-4.0, -3.0)
step 8: pos (4.0, 0.0) vel (-4.0, 3.0)

Hint: The left wall's inward normal is (1, 0), the right wall's (-1, 0), the floor's (0, 1) and the ceiling's (0, -1).

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

struct Vec2 { double x, y; };
Vec2 operator+(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
Vec2 operator*(Vec2 v, double s) { return {v.x * s, v.y * s}; }
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }

Vec2 reflect(Vec2 v, Vec2 n) { return v - n * (2 * dot(v, n)); }

int main() {
    std::cout << std::fixed << std::setprecision(1);
    Vec2 pos{2, 3}, vel{4, 3};
    const double dt = 0.5;
    for (int step = 1; step <= 8; step++) {
        pos = pos + vel * dt;
        if (pos.x < 0)  { pos.x = 0;  vel = reflect(vel, {1, 0}); }
        if (pos.x > 10) { pos.x = 10; vel = reflect(vel, {-1, 0}); }
        if (pos.y < 0)  { pos.y = 0;  vel = reflect(vel, {0, 1}); }
        if (pos.y > 6)  { pos.y = 6;  vel = reflect(vel, {0, -1}); }
        std::cout << "step " << step << ": pos (" << pos.x << ", " << pos.y << ") vel (" << vel.x << ", " << vel.y << ")\n";
    }
}

Exercise 4: Turret angles

Print the angle (in degrees, -180..180) from the turret to each target, and which way it must turn from its current heading of 90° (the shortest way).

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

struct Vec2 { double x, y; };

double wrap180(double deg) {
    // TODO: wrap any angle into [-180, 180)
    return deg;
}

int main() {
    std::cout << std::fixed << std::setprecision(1);
    Vec2 turret{1, 1};
    const double heading = 90;
    Vec2 targets[] = {{4, 4}, {1, 5}, {-2, 1}, {3, -2}};
    for (Vec2 t : targets) {
        double angle = 0;               // TODO: atan2 of the arrow from the turret to t, in degrees
        double turn = wrap180(angle - heading);
        std::cout << "target (" << t.x << ", " << t.y << "): angle " << angle << ", turn " << turn
                  << (turn > 0 ? " (left)" : turn < 0 ? " (right)" : "") << "\n";
    }
}
target (4.0, 4.0): angle 0.0, turn -90.0 (right)
target (1.0, 5.0): angle 0.0, turn -90.0 (right)
target (-2.0, 1.0): angle 0.0, turn -90.0 (right)
target (3.0, -2.0): angle 0.0, turn -90.0 (right)

Expected output when solved:

text
target (4.0, 4.0): angle 45.0, turn -45.0 (right)
target (1.0, 5.0): angle 90.0, turn 0.0
target (-2.0, 1.0): angle 180.0, turn 90.0 (left)
target (3.0, -2.0): angle -56.3, turn -146.3 (right)

Hint: std::atan2(dy, dx) takes y first. For the wrap, std::fmod can return negative values, so fix them up.

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

struct Vec2 { double x, y; };

double wrap180(double deg) {
    deg = std::fmod(deg + 180, 360);
    if (deg < 0) deg += 360;
    return deg - 180;
}

int main() {
    std::cout << std::fixed << std::setprecision(1);
    Vec2 turret{1, 1};
    const double heading = 90;
    Vec2 targets[] = {{4, 4}, {1, 5}, {-2, 1}, {3, -2}};
    for (Vec2 t : targets) {
        double angle = std::atan2(t.y - turret.y, t.x - turret.x) * 180 / std::numbers::pi;
        double turn = wrap180(angle - heading);
        std::cout << "target (" << t.x << ", " << t.y << "): angle " << angle << ", turn " << turn
                  << (turn > 0 ? " (left)" : turn < 0 ? " (right)" : "") << "\n";
    }
}

Exercise 5: Local and world

A crane's hook hangs at local point (3, -1) relative to the crane, which is rotated by 90° and placed at (10, 2). Complete localToWorld (rotate, then translate) and worldToLocal (the inverse: subtract, then rotate by -angle).

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

struct Vec2 { double x, y; };
struct Pose { Vec2 pos; double angle; };          // angle in radians

Vec2 rotate(Vec2 v, double a) {
    double c = std::cos(a), s = std::sin(a);
    return {v.x * c - v.y * s, v.x * s + v.y * c};
}
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }

Vec2 localToWorld(const Pose& p, Vec2 local) {
    return local;                                 // TODO
}
Vec2 worldToLocal(const Pose& p, Vec2 world) {
    return world;                                 // TODO
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    Pose crane{{10, 2}, std::numbers::pi / 2};
    Vec2 hook = localToWorld(crane, {3, -1});
    Vec2 back = worldToLocal(crane, hook);
    Vec2 crate = worldToLocal(crane, {8, 5});
    std::cout << "hook in world:   (" << z0(hook.x) << ", " << z0(hook.y) << ")\n";
    std::cout << "hook back:       (" << z0(back.x) << ", " << z0(back.y) << ")\n";
    std::cout << "crate in local:  (" << z0(crate.x) << ", " << z0(crate.y) << ")\n";
}
hook in world:   (3.000, -1.000)
hook back:       (3.000, -1.000)
crate in local:  (8.000, 5.000)

Expected output when solved:

text
hook in world:   (11.000, 5.000)
hook back:       (3.000, -1.000)
crate in local:  (3.000, 2.000)
Show solution
cpp
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numbers>

struct Vec2 { double x, y; };
struct Pose { Vec2 pos; double angle; };

Vec2 rotate(Vec2 v, double a) {
    double c = std::cos(a), s = std::sin(a);
    return {v.x * c - v.y * s, v.x * s + v.y * c};
}
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }

Vec2 localToWorld(const Pose& p, Vec2 local) {
    Vec2 r = rotate(local, p.angle);
    return {r.x + p.pos.x, r.y + p.pos.y};
}
Vec2 worldToLocal(const Pose& p, Vec2 world) {
    return rotate({world.x - p.pos.x, world.y - p.pos.y}, -p.angle);
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    Pose crane{{10, 2}, std::numbers::pi / 2};
    Vec2 hook = localToWorld(crane, {3, -1});
    Vec2 back = worldToLocal(crane, hook);
    Vec2 crate = worldToLocal(crane, {8, 5});
    std::cout << "hook in world:   (" << z0(hook.x) << ", " << z0(hook.y) << ")\n";
    std::cout << "hook back:       (" << z0(back.x) << ", " << z0(back.y) << ")\n";
    std::cout << "crate in local:  (" << z0(crate.x) << ", " << z0(crate.y) << ")\n";
}

Exercise 6: Quaternion turns

Complete axisAngle (remember the half angle) and use it to rotate the forward vector (0, 0, -1) by: 90° around Y; 90° around X; and the combination "first 90° around X, then 90° around Y".

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

struct Vec3 { double x, y, z; };
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
struct Quat { double w, x, y, z; };
Quat operator*(Quat a, Quat b) {
    return {a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z, a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
            a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w};
}
Vec3 rotate(Quat q, Vec3 v) { Vec3 u{q.x, q.y, q.z}; Vec3 t = cross(u, v) * 2; return v + t * q.w + cross(u, t); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec3 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ", " << z0(v.z) << ")"; }

Quat axisAngle(Vec3 axis, double degrees) {
    return {1, 0, 0, 0};          // TODO: (cos(a/2), axis * sin(a/2)), a in radians
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    Vec3 forward{0, 0, -1};
    Quat yaw = axisAngle({0, 1, 0}, 90), pitch = axisAngle({1, 0, 0}, 90);
    std::cout << "yaw 90:         " << rotate(yaw, forward) << "\n";
    std::cout << "pitch 90:       " << rotate(pitch, forward) << "\n";
    std::cout << "pitch then yaw: " << rotate(yaw * pitch, forward) << "\n";    // TODO: check the order
}
yaw 90:         (0.000, 0.000, -1.000)
pitch 90:       (0.000, 0.000, -1.000)
pitch then yaw: (0.000, 0.000, -1.000)

Expected output when solved:

text
yaw 90:         (-1.000, 0.000, 0.000)
pitch 90:       (0.000, 1.000, 0.000)
pitch then yaw: (0.000, 1.000, 0.000)

Hint: q2 * q1 applies q1 first. Pitching up first and then turning still looks straight up.

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

struct Vec3 { double x, y, z; };
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
struct Quat { double w, x, y, z; };
Quat operator*(Quat a, Quat b) {
    return {a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z, a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
            a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w};
}
Vec3 rotate(Quat q, Vec3 v) { Vec3 u{q.x, q.y, q.z}; Vec3 t = cross(u, v) * 2; return v + t * q.w + cross(u, t); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec3 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ", " << z0(v.z) << ")"; }

Quat axisAngle(Vec3 axis, double degrees) {
    double h = degrees * std::numbers::pi / 180 / 2, s = std::sin(h);
    return {std::cos(h), axis.x * s, axis.y * s, axis.z * s};
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    Vec3 forward{0, 0, -1};
    Quat yaw = axisAngle({0, 1, 0}, 90), pitch = axisAngle({1, 0, 0}, 90);
    std::cout << "yaw 90:         " << rotate(yaw, forward) << "\n";
    std::cout << "pitch 90:       " << rotate(pitch, forward) << "\n";
    std::cout << "pitch then yaw: " << rotate(yaw * pitch, forward) << "\n";
}

Exercise 7: Fix the follow camera

The camera follows a target with a constant lerp factor, so it ends up in different places at 30 and 120 FPS. Change the factor so both frame rates give the same result after one second, with a speed of 6.

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

double followOneSecond(int fps) {
    double cam = 0, target = 10, dt = 1.0 / fps;
    for (int i = 0; i < fps; i++) {
        double t = 0.1;               // TODO: frame-rate independent factor using dt and speed 6
        cam = cam + (target - cam) * t;
    }
    return cam;
}

int main() {
    std::cout << std::fixed << std::setprecision(4);
    std::cout << "30 FPS:  " << followOneSecond(30) << "\n";
    std::cout << "120 FPS: " << followOneSecond(120) << "\n";
}
30 FPS:  9.5761
120 FPS: 10.0000

Expected output when solved:

text
30 FPS:  9.9752
120 FPS: 9.9752
Show solution
cpp
#include <iostream>
#include <iomanip>
#include <cmath>

double followOneSecond(int fps) {
    double cam = 0, target = 10, dt = 1.0 / fps;
    for (int i = 0; i < fps; i++) {
        double t = 1 - std::exp(-6 * dt);
        cam = cam + (target - cam) * t;
    }
    return cam;
}

int main() {
    std::cout << std::fixed << std::setprecision(4);
    std::cout << "30 FPS:  " << followOneSecond(30) << "\n";
    std::cout << "120 FPS: " << followOneSecond(120) << "\n";
}

Exercise 8: Click to select

A mouse ray goes from the camera at the origin along (0, 0, -1). Complete raySphere (unit direction; return the entry distance, or -1 for a miss, ignoring spheres behind the camera) and print the name of the closest sphere hit.

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

struct Vec3 { double x, y, z; };
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }

double raySphere(Vec3 o, Vec3 d, Vec3 c, double r) {
    // TODO: b = dot(o - c, d); q = dot(o - c, o - c) - r*r; disc = b*b - q; t = -b - sqrt(disc)
    return -1;
}

struct Unit { std::string name; Vec3 center; double radius; };

int main() {
    std::cout << std::fixed << std::setprecision(2);
    std::vector<Unit> units = {
        {"archer", {0.5, 0, -9}, 1.0}, {"knight", {-0.3, 0.2, -6}, 0.8},
        {"tower", {0, 0, -20}, 3.0}, {"ghost", {0, 0, 4}, 1.0}, {"horse", {2, 0, -5}, 1.0},
    };
    Vec3 o{0, 0, 0}, d{0, 0, -1};
    std::string best = "nothing";
    double bestT = 1e30;
    for (const auto& u : units) {
        double t = raySphere(o, d, u.center, u.radius);
        if (t >= 0) std::cout << u.name << " hit at " << t << "\n";
        if (t >= 0 && t < bestT) { bestT = t; best = u.name; }
    }
    std::cout << "selected: " << best << "\n";
}
selected: nothing

Expected output when solved:

text
archer hit at 8.13
knight hit at 5.29
tower hit at 17.00
selected: knight
Show solution
cpp
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <vector>

struct Vec3 { double x, y, z; };
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }

double raySphere(Vec3 o, Vec3 d, Vec3 c, double r) {
    Vec3 oc = o - c;
    double b = dot(oc, d), q = dot(oc, oc) - r * r;
    double disc = b * b - q;
    if (disc < 0) return -1;
    double t = -b - std::sqrt(disc);
    if (t < 0) t = -b + std::sqrt(disc);     // inside the sphere
    return t;                                 // still negative if the sphere is behind
}

struct Unit { std::string name; Vec3 center; double radius; };

int main() {
    std::cout << std::fixed << std::setprecision(2);
    std::vector<Unit> units = {
        {"archer", {0.5, 0, -9}, 1.0}, {"knight", {-0.3, 0.2, -6}, 0.8},
        {"tower", {0, 0, -20}, 3.0}, {"ghost", {0, 0, 4}, 1.0}, {"horse", {2, 0, -5}, 1.0},
    };
    Vec3 o{0, 0, 0}, d{0, 0, -1};
    std::string best = "nothing";
    double bestT = 1e30;
    for (const auto& u : units) {
        double t = raySphere(o, d, u.center, u.radius);
        if (t >= 0) std::cout << u.name << " hit at " << t << "\n";
        if (t >= 0 && t < bestT) { bestT = t; best = u.name; }
    }
    std::cout << "selected: " << best << "\n";
}

Test yourself

In Exercise 1, why snap to the player when the remaining distance is below speed * dt?

  1. To save a square root
  2. Otherwise the enemy would overshoot and jitter around the player
  3. Because normalize fails for long vectors
  4. It is required by C++

In Exercise 3, what is the inward normal of the right wall of the box?

  1. (1, 0)
  2. (-1, 0)
  3. (0, 1)
  4. (0, -1)

In Exercise 6, which product applies the pitch first and the yaw second?

  1. pitch * yaw
  2. yaw * pitch
  3. pitch + yaw
  4. Either