Field Notes
The formulas in this course are the easy part. The bugs come from habits: a missing normalize, a float compared with ==, a lerp with a constant factor, an asset imported with the wrong axis. These are the lessons game programmers usually learn by shipping a bug first.
1. Normalize before you dot
dot(a, b) only means "cosine of the angle" when both vectors are unit length. Without normalizing, a distant target scores higher than a close one in a field-of-view check, and lighting gets brighter on bigger meshes. Rules of thumb:
- Normalize directions once, where they are created (input,
target - position, normals at import). - Name variables by meaning:
dirToTargetis unit length,toTargetis not. - Use the engine's safe normalize (
GetSafeNormal,normalized,normalizesafe) anywhere a zero vector is possible: a player standing exactly on a waypoint, a zero velocity, two objects spawned at the same spot.
2. Compare floats with an epsilon
Floating-point math rounds. 0.1 + 0.2 == 0.3 is false, and "has the door finished opening?" written as angle == 90.0f may never be true. Compare with a tolerance, and pick the tolerance for the scale of the values:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
bool nearlyEqual(double a, double b, double absEps = 1e-6, double relEps = 1e-6) {
double diff = std::fabs(a - b);
if (diff <= absEps) return true; // near zero
return diff <= relEps * std::max(std::fabs(a), std::fabs(b)); // large values
}
int main() {
std::cout << std::boolalpha << std::setprecision(17);
double a = 0.1 + 0.2;
std::cout << "0.1 + 0.2 = " << a << "\n";
std::cout << "== 0.3: " << (a == 0.3) << ", nearlyEqual: " << nearlyEqual(a, 0.3) << "\n";
float door = 0;
for (int i = 0; i < 900; i++) door += 0.1f; // 900 steps of 0.1 degree
std::cout << std::setprecision(9) << "door angle " << door << ": == 90 " << (door == 90.0f)
<< ", nearlyEqual " << nearlyEqual(door, 90.0, 1e-3, 1e-5) << "\n";
}0.1 + 0.2 = 0.30000000000000004
== 0.3: false, nearlyEqual: true
door angle 89.9991989: == 90 false, nearlyEqual true
Better still, avoid the equality question: clamp the value (angle = std::min(angle + step, 90.0f)) and the end state becomes exact.
3. Never lerp with a constant factor per frame
x = lerp(x, target, 0.1f) in Update runs faster on fast machines. Use 1 - exp(-speed * dt) as the factor, or the engine's damping helper (SmoothDamp, FInterpTo, MathUtils.damp). The same goes for Slerp toward a target rotation. Test any "smooth follow" at 30 FPS and 144 FPS; many engines let you cap the frame rate (Application.targetFrameRate, t.MaxFPS, Engine.max_fps).
4. Most import bugs are handedness or units
Unity is left-handed Y-up, Unreal left-handed Z-up in centimeters, Godot and Three.js right-handed Y-up, Blender right-handed Z-up. When a model arrives lying down, mirrored, inside-out, or 100 times too big:
- lying on its back: up axis (Z-up vs Y-up), fix in the exporter's axis settings;
- mirrored text or inside-out faces: handedness flip without reversing triangle winding;
- 100× wrong: centimeters vs meters;
- facing backward: forward axis (+Z vs -Z vs +X).
Keep a 1 m test cube with an arrow and some text in the repository and import it whenever the pipeline changes.
5. Floats lose precision far from the origin
A 32-bit float has 24 bits of mantissa: about 7 significant digits. At 10 km from the origin, the smallest step between representable positions is about 1 mm; at 100 km it is about 8 mm, enough to make cameras and animations jitter visibly.
#include <iostream>
#include <iomanip>
#include <cmath>
int main() {
std::cout << std::setprecision(4);
for (float pos : {1.0f, 100.0f, 10000.0f, 100000.0f, 1000000.0f}) {
float next = std::nextafter(pos, 2 * pos);
std::cout << "at " << std::setw(7) << long(pos) << " m the next float is " << (next - pos) * 1000 << " mm away\n";
}
}at 1 m the next float is 0.0001192 mm away
at 100 m the next float is 0.007629 mm away
at 10000 m the next float is 0.9766 mm away
at 100000 m the next float is 7.812 mm away
at 1000000 m the next float is 62.5 mm away
Fixes, in order of effort: keep levels within a few kilometers; origin rebasing (periodically shift the whole world so the player is near 0, as Unity open-world games and Godot's large-world setups do); or doubles for world positions, which Unreal Engine 5 does by default ("Large World Coordinates") and Godot offers as a precision=double build.
6. Know which way your matrices go
When a transform is wrong, check in this order:
- Order of multiplication:
T * R * Swith column vectors (GLM, Unity'sMatrix4x4),S * R * Twith row vectors (DirectXMath, System.Numerics). - Points vs directions:
w = 1vsw = 0(TransformPointvsTransformDirection). - Local vs world:
transform.rotationvstransform.localRotation;positionvsglobal_position. - Storage order when sending matrices to a shader.
Print one simple case (a translation of (5, 6, 7), a 90° rotation of (1, 0, 0)) instead of staring at the full scene.
7. Prefer dot products and squared distances in hot code
acos, atan2, sqrt and normalizing aren't slow, but they add up when run for every enemy against every bullet. Compare dot(dir, forward) > cosHalfFov instead of computing angles; compare distSq < range * range instead of distances. Keep the readable version in a comment if needed.
8. Store angles and rebuild, don't accumulate
rotation = rotation * smallTurn every frame accumulates rounding error, and after minutes the quaternion is no longer unit length. A first-person camera should store yaw and pitch as floats, clamp pitch to ±89°, and rebuild the rotation from them every frame. When you must accumulate (physics integration), renormalize after each step.
9. Seed everything that must be reproducible
Every procedural system gets its own generator seeded from the world seed (worldSeed ^ hash("loot")). Log the seed with every bug report. Never use std::rand, Math.random or an unseeded Random for gameplay that has to replay or sync over the network, and remember that <random> distributions differ between compilers.
10. Debug-draw the math
Every engine can draw lines and spheres for one frame: Unity's Debug.DrawRay and Gizmos, Unreal's DrawDebugLine/DrawDebugSphere, Godot's DebugDraw add-ons or an ImmediateMesh, Three.js ArrowHelper. Draw the forward vector, the vision cone, the ray, the normal at the hit point. A wrong sign or a missing normalize is obvious in a picture and invisible in a log of numbers.
Test yourself
Why can angle == 90.0f never become true for a door that opens in small float steps?
- Floats can't store 90
- Rounding errors in each step make the sum land slightly off
- Doors use radians
- == is not defined for floats
A camera jitters when the player is 80 km from the origin. What is the likely cause?
- Gimbal lock
- 32-bit float precision at large coordinates
- Wrong handedness
- A missing normalize
What is the safer way to implement a first-person camera's rotation?
- Multiply the rotation by a small turn every frame forever
- Store yaw and pitch, clamp pitch, and rebuild the rotation each frame
- Use three Euler angles including roll
- Read the Euler angles back from the transform each frame