Top 100 Game Programmer Interview Questions and Answers
The questions most likely to come up in your Game Programmer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.
Curated: · Written: · Reviewed: —
Q&A-1A projectile effect locks the physics world and allocates a temporary GPU buffer, but an early return and a throwing render call can skip cleanup. Walk me through how RAII guarantees release on both paths and what manual cleanup gets wrong?
The 90-second answer
RAII binds a resource to an object. The constructor acquires it, the destructor releases it, and C++ guarantees the destructor runs when the object leaves scope. That guarantee covers a normal return, an early return, and stack unwinding when an exception propagates. Manual cleanup has none of those guarantees. It runs only if the programmer remembers to call it on every path, including paths added later.
In a game loop that difference shows up fast. A projectile effect that runs every frame can leak a lock or a GPU buffer on one rare path. One leak is invisible. Sixty leaks a second exhausts the driver or deadlocks the physics thread within a minute.
The situation
Firing a projectile needs two things for the duration of one function: exclusive access to the physics world while spawning bodies, and a temporary GPU buffer for a trail render pass. Both must be gone before the function returns, whatever happens inside.
// C++17
#include <mutex>
class ScopedLock {
public:
explicit ScopedLock(std::mutex& m) : m_(m) { m_.lock(); }
~ScopedLock() { m_.unlock(); }
ScopedLock(const ScopedLock&) = delete;
ScopedLock& operator=(const ScopedLock&) = delete;
private:
std::mutex& m_;
};
class GpuBuffer {
public:
GpuBuffer(unsigned bytes, void* device) : device_(device) {
handle_ = CreateBuffer(device_, bytes);
}
~GpuBuffer() { DestroyBuffer(device_, handle_); }
GpuBuffer(const GpuBuffer&) = delete;
GpuBuffer& operator=(const GpuBuffer&) = delete;
private:
void* device_;
void* handle_ = nullptr;
};
void FireProjectile(std::mutex& physics, void* device, bool valid) {
ScopedLock lock(physics);
GpuBuffer trail(256 * 256 * 4, device);
if (!valid) return; // early return path
RenderTrail(trail); // may throw
} // trail destroyed, then lock released, in reverse orderTrace: early return
| Step | What happens | Cleanup |
|---|---|---|
| 1 | ScopedLock constructed, mutex acquired | None yet |
| 2 | GpuBuffer constructed, buffer created | None yet |
| 3 | valid is false, return executes | Compiler inserts destructor calls |
| 4 | Scope exits | trail destroyed first, then lock released |
| 5 | Caller resumes | Mutex free, buffer freed |
Trace: exception
| Step | What happens | Cleanup |
|---|---|---|
| 1 | RenderTrail throws | None yet |
| 2 | Stack unwinding starts at the throw site | Destructors run for each live local |
| 3 | Unwinding reaches FireProjectile scope | trail destroyed, then lock released |
| 4 | Exception reaches caller | Both resources already released |
Reverse order matters here. The buffer was created after the lock, so it is destroyed before the lock is released. No code can touch the buffer after the physics world becomes visible to other threads.
Manual cleanup compared
| Path | Manual DestroyBuffer plus mutex release | RAII |
|---|---|---|
| Normal return | Runs if called | Runs |
| Early return added later | Skipped unless every return is audited | Runs |
Exception from RenderTrail | Skipped, mutex stays held, buffer leaks | Runs during unwinding |
New developer adds a break or continue | Easy to miss one site | Runs at scope exit |
With manual cleanup the early return in the code above would need a release call before it, the throwing call would need a try/catch that releases and rethrows, and every future exit would need the same treatment. Miss one and the next projectile thread blocks on the mutex forever. The failure looks like a hang in physics, not a leak in the effect code, which makes it expensive to diagnose from a crash dump.
Failure modes to name in the interview
A destructor that throws is the first. If DestroyBuffer throws while unwinding, the program calls std::terminate. Destructors are noexcept by default for this reason. Log the error, do not propagate it.
Double ownership is the second. If two objects both believe they own the same handle, both destructors run and the second release is undefined behaviour. Deleting copy operations, as above, makes that a compile error. Transfer of ownership goes through a move that nulls the source.
The third is a wrapper that does not actually own anything. A class holding a raw pointer with an empty destructor gives the appearance of RAII and none of the guarantee. The standard library versions, std::lock_guard for a mutex and std::unique_ptr with a custom deleter for a GPU handle, exist so most gameplay code does not need hand-written wrappers at all.
The mechanism is simple: acquire in the constructor, release in the destructor, let scope decide when that happens. The payoff is that cleanup survives early returns and exceptions without the caller having to think about them.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2If two game objects each hold a shared_ptr to the other, what happens when the rest of the game releases them?
The 90-second answer
They leak. Neither object is ever destroyed.
Each shared_ptr keeps the object it points to alive until its own refcount reaches zero. If A holds a shared_ptr to B and B holds a shared_ptr to A, each count stays at one even after every other owner has gone away. The destructor never runs for either object.
// C++17
struct Inventory {
std::shared_ptr<Character> owner;
};
struct Character {
std::shared_ptr<Inventory> inventory;
};
{
auto c = std::make_shared<Character>();
c->inventory = std::make_shared<Inventory>();
c->inventory->owner = c;
} // c goes out of scope, but both counts stay at 1Trace it by the counts. After the block, Character has count 1 from Inventory::owner and Inventory has count 1 from Character::inventory. No count reaches zero, so neither destructor runs. Repeat that on every level load and memory climbs by one character and one inventory each time.
The fix is to make one direction a weak_ptr. A weak_ptr observes the object without keeping it alive, so it does not add to the count.
struct Inventory {
std::weak_ptr<Character> owner; // back reference, does not extend lifetime
};Now releasing the last shared_ptr to Character drops its count to zero and destroys it. That destroys its shared_ptr to Inventory, whose count then drops to zero too. Both are freed.
When you use a weak_ptr, check it before use. lock() returns a temporary shared_ptr if the object is still alive and an empty one if it has expired.
if (auto c = inventory->owner.lock()) {
c->UseItem();
}That is why a back reference, a parent pointer, or a cache entry should normally be weak. The owning direction stays shared_ptr. The observing direction stays weak_ptr.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Your LevelBuffer logs in its destructor, is returned by value from a streaming factory, stored in a std::vector<LevelBuffer>, and reused after a move to load the next level. Walk me through the Rule of Five implementation that keeps all four paths copy-free and safe, and what breaks if a special member is missing?
The 90-second answer
Declare all five special members, make the move operations noexcept, and leave a moved-from buffer in a state that can be destroyed and reused. The custom destructor is the trap. Declaring it suppresses the implicit move constructor and move assignment, so return buf; and vector growth fall back to copying. With a 64 MiB buffer that turns a pointer transfer into an allocation plus a memcpy on every return, every assignment, and every reallocation.
// C++20
class LevelBuffer {
public:
LevelBuffer() = default;
explicit LevelBuffer(std::size_t bytes) : data_(bytes) {}
~LevelBuffer() { LogDestroy(data_.size()); }
LevelBuffer(const LevelBuffer& other) : data_(other.data_) {}
LevelBuffer& operator=(const LevelBuffer& other) {
if (this != &other) data_ = other.data_;
return *this;
}
LevelBuffer(LevelBuffer&& other) noexcept
: data_(std::move(other.data_)) {}
LevelBuffer& operator=(LevelBuffer&& other) noexcept {
if (this != &other) data_ = std::move(other.data_);
return *this;
}
std::byte* data() { return data_.data(); }
std::size_t size() const { return data_.size(); }
void ReuseForNextLevel(std::size_t bytes) { data_.assign(bytes, std::byte{}); }
private:
std::vector<std::byte> data_;
};
static_assert(std::is_nothrow_move_constructible_v<LevelBuffer>);
static_assert(std::is_nothrow_move_assignable_v<LevelBuffer>);
LevelBuffer LoadLevel(std::string_view path) {
LevelBuffer buf(64u << 20); // 64 MiB in this example
FillFromDisk(path, buf);
return buf; // NRVO if the compiler applies it, otherwise one move
}How the four paths interact
| Path | Correct implementation | Missing member and result |
|---|---|---|
| Factory return of a named local | NRVO or move constructor. Pointer, size and capacity transfer. | Destructor only: move is suppressed, copy constructor runs. One allocation and a 64 MiB copy. |
Factory return of a prvalue, return LevelBuffer{size}; | Guaranteed elision in C++17. No move or copy runs. | Still elided. This path hides the bug in tests that only use prvalues. |
levels.push_back(LoadLevel(p)) and vector growth | std::vector uses move_if_noexcept. A noexcept move transfers each buffer during reallocation. | Move missing or throwing: vector copies every existing element to keep the strong guarantee. Eight levels means eight copies. |
Reuse after move, old.ReuseForNextLevel(n) | Moved-from vector is valid and empty, so assign reallocates cleanly. Destruction is safe. | Raw pointer version that forgets to null the source: double free on destruction, or stale size reported to the streaming code. |
The vector case is where senior candidates separate from textbook answers. The move can exist and still never be used for growth. If it is not marked noexcept, move_if_noexcept selects the copy constructor. The code compiles, the factory return looks fast in isolation, and the hitch appears only when the ninth level is pushed and the vector reallocates. At roughly 20 GB/s memory bandwidth, copying eight 64 MiB buffers moves 512 MiB and costs about 25 ms, plus eight allocations. That lands on the loading thread if you are lucky and on the main thread if the push happens during a transition.
Trace with the destructor present and no move declared
Assume 64 MiB per level, hypothetical but realistic for uncompressed geometry and texture data.
LoadLevelallocates 64 MiB and fills it in place.return buf;calls the copy constructor because the user-declared destructor suppressed the move. A second 64 MiB allocation appears and the bytes are copied.- The caller assigns the result. Copy assignment runs for the same reason, allocating again.
- The vector grows from four to eight levels. Each element is copied into the new storage.
- Destruction frees each allocation once, so there is no crash. The failure is cost and peak memory. Peak usage during step 2 is 128 MiB for one level, which can fail on a memory-capped target even though the steady state needs 64 MiB.
Failure modes to name in the interview
Self-move assignment. buf = std::move(buf) reaches the move assignment with this == &other. Without the identity check, the member is moved from itself and the buffer can be emptied or freed depending on the implementation. Generic code that moves through a reference triggers this more often than factory code does.
Moved-from reuse with a hand-rolled allocation. If the member were std::byte* ptr_ plus a size, the move would need to null the source pointer and zero the size. Skipping that leaves two objects owning one allocation. The vector member in the code above handles this, which is why the Rule of Zero would be preferable without the telemetry destructor. Once you need the destructor, you pay for writing all five correctly.
Exception safety during vector reallocation. A noexcept move that only transfers a vector cannot throw. Marking it noexcept when the body could throw would call std::terminate on error instead. The static_asserts above catch a mismatch at compile time.
Detection is a test, not a review comment. Assert nothrow move constructibility, count allocations in a debug allocator for one LoadLevel round trip, and profile a push that forces reallocation. A correct version shows one allocation in the factory and zero allocations during growth. Any extra allocation points at a suppressed or non-noexcept move, regardless of how clean the class looks on the page.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4How do you handle temporary vectors created every frame, and why does heap allocation there cause hitches?
The 90-second answer
For a temporary vector that lives for one frame, I keep it on the stack or in a frame-scoped scratch buffer, not on the heap. Stack allocation is a pointer bump. Heap allocation is a search through free lists, with metadata, possible locking, and latency that varies from frame to frame. In a 60 fps game I have 16.7 ms per frame, and a hitch is not the average cost. It is the one frame where the allocator takes the slow path.
// Bad: allocates on the heap every frame, even if the vector stays small
void UpdateBad() {
std::vector<Vec3> hits;
hits.reserve(8); // still a heap allocation
// ... fill hits, use them, destroy them
}
// Good: fixed-size stack storage for a known small bound
void UpdateGood() {
std::array<Vec3, 8> hits{};
int hitCount = 0;
// ... fill hits[hitCount++] while hitCount < 8
}
// Good when the count is unbounded but the lifetime is one frame:
// a bump allocator reset at the end of the frame
struct FrameAllocator {
Vec3* data;
int capacity;
int used = 0;
Vec3* Alloc(int n) {
Vec3* p = data + used;
used += n; // caller guarantees used <= capacity
return p;
}
void Reset() { used = 0; }
};The stack case works because the compiler knows the size at compile time and the lifetime is the enclosing scope. Allocation is sub rsp, 96 or similar, deallocation is the same instruction on return. The memory is already in cache because the function is running. There is no free list to search and no other thread to contend with.
A frame allocator gives the same property for variable counts. I allocate one large block at startup, hand out slices with a bump pointer during the frame, and reset the pointer to zero at the end. No per-object free, so no fragmentation inside the frame.
| Stack / frame buffer | Heap (new, malloc, std::vector) | |
|---|---|---|
| Cost | Pointer bump, O(1), predictable | Free-list search, metadata update, possible lock |
| Latency | Same every frame | Fast path and slow path differ by orders of magnitude |
| Fragmentation | None within the frame | Grows over time as sizes vary |
| Lifetime | Scope-bound, automatic | Manual or RAII, easy to get wrong |
| Limit | Small, fixed or preallocated size | Large or long-lived data |
Why the heap causes hitches, not just slowness
Hypothetical but typical figures for a mid-range PC: a stack bump is a few nanoseconds, a malloc fast path is tens to a few hundred nanoseconds, and a slow path that splits a block, takes a lock, or touches a fresh page can be microseconds to milliseconds. The average looks fine. The tail is the problem.
Trace of a frame loop allocating, say, 300 small vectors per frame:
| Frame | Work | Allocation behaviour | Frame time |
|---|---|---|---|
| 1-59 | Gameplay | Fast path, blocks reused | 8-11 ms |
| 60 | Gameplay, pool fragmented after a level transition | Allocator splits blocks, touches new pages | 34 ms |
| 61 | Gameplay | Back to fast path | 9 ms |
Frame 60 misses the 16.7 ms budget by 2x. The player sees a stutter, not a lower average frame rate. Fragmentation makes this worse over a session: freed blocks of different sizes leave holes the allocator must search, and a large allocation may need a fresh OS page, which costs a page fault and a zeroing pass.
In C# or Unity the same issue appears as GC pressure. Every new Vector3[] or new List<T>() per frame adds to the generation 0 heap, and the collector pauses to reclaim it. The mechanism differs, the tail latency does not.
Where I would still use the heap
Long-lived data, data whose size I cannot bound at startup, and data shared across frames or systems. A level's collision mesh, a persistent entity pool, a network receive buffer that grows to a protocol maximum. For those I allocate once, reserve capacity, and reuse. The rule I apply is: if the lifetime is one frame and the size is small or preallocatable, it never touches the heap. If it must, I allocate outside the frame loop and keep the allocation count at zero during gameplay.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5If update takes 5 ms, physics 4 ms and render 6 ms in a 16.6 ms frame at 60 fps, how would you break down the budget and decide what to trim first?
The 90-second answer
At 60 fps the frame budget is 1000 divided by 60, which is 16.67 ms. I split that across the stages that run on the CPU and keep the rest as headroom for spikes.
| Stage | Budget | Typical work |
|---|---|---|
| Update | 4.0 ms | Input, gameplay logic, AI, animation |
| Physics | 3.0 ms | Collision detection, solver, character movement |
| Render | 5.0 ms | Culling, draw calls, shadow and post setup |
| Headroom | 4.67 ms | OS jitter, driver work, occasional spikes |
| Total | 16.67 ms |
With update at 5 ms, physics at 4 ms and render at 6 ms, the total is 15 ms. That leaves only 1.67 ms of headroom, so the frame will pass on a quiet scene and miss as soon as anything spikes. I would treat that as over budget even though 15 is less than 16.67.
How I measure it
I time each stage separately instead of timing the whole frame. A scope timer writes the result into a ring buffer, and the debug view draws the last 300 frames as stacked bars.
// C++17, frame timing with a simple scope guard
struct StageTimer {
float& slot;
std::chrono::steady_clock::time_point start;
StageTimer(float& out) : slot(out), start(std::chrono::steady_clock::now()) {}
~StageTimer() {
slot = std::chrono::duration<float, std::milli>(
std::chrono::steady_clock::now() - start).count();
}
};
float updateMs = 0, physicsMs = 0, renderMs = 0;
// Inside the frame loop:
{ StageTimer t(updateMs); UpdateGame(dt); }
{ StageTimer t(physicsMs); StepPhysics(dt); }
{ StageTimer t(renderMs); SubmitRender(); }I also record the GPU time from the graphics API timestamp query, because CPU submission and GPU execution overlap. A frame can have 12 ms of CPU work and still miss if the GPU needs 18 ms to draw it.
What to trim first
A worked trace from a scene with many characters shows the pattern:
| Stage | Measured | Budget | Excess |
|---|---|---|---|
| Update | 5.0 ms | 4.0 ms | 1.0 ms |
| Physics | 4.0 ms | 3.0 ms | 1.0 ms |
| Render | 6.0 ms | 5.0 ms | 1.0 ms |
I look for the cheapest fix in each stage before cutting features. In update, that was AI ticking every frame for every character. Ticking half the characters each frame, on alternate frames, dropped update to 3.4 ms with no visible change. In physics, capping the solver to a fixed number of iterations and using a fixed timestep with at most two substeps per frame dropped physics to 2.8 ms. In render, merging static geometry and reducing shadow casters dropped render to 4.6 ms.
The new total is 10.8 ms, which restores about 5.8 ms of headroom. I then run the heaviest scene for several minutes on the minimum target machine and check the tail, not just the average. If the 99th percentile frame is still above 16.67 ms, the budget for that stage is too tight and needs a real cut, such as fewer particles or a lower shadow resolution, rather than hoping the spike goes away.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Walk me through how you would use a CPU profiler and RenderDoc to tell whether a frame spike is CPU-bound or GPU-bound?
The 90-second answer
Capture the spike, do not guess from average FPS. I run the CPU profiler and RenderDoc on the same frame, then compare CPU time, GPU time, and idle time against the frame budget. At 60 FPS that budget is 16.6 ms. If the CPU needs more than that to submit work, the GPU will sit idle waiting for commands and the frame is CPU-bound. If the CPU submits early and then waits while the GPU is busy for most of the frame, it is GPU-bound.
A useful trace looks like this (hypothetical figures from a 60 FPS target):
Median frame 1234
CPU main thread |##########......................| 9 ms
GPU | ###########...................| 11 ms
Spike frame 1235
CPU main thread |############################...| 28 ms
GPU | ###########...................| 11 ms, 17 ms idleIn the spike, GPU work did not grow. The main thread did, so the GPU starved. That points at game logic, physics, animation, culling, or draw submission on the CPU, not at shading.
What I look for in each tool
In a CPU profiler such as Tracy, Unreal Insights, or the Visual Studio profiler, I check the main thread first, then the render thread and job workers. A spike that appears as one long main-thread marker, for example physics stepping or UpdateAnimation, is a CPU cost. A spike split across many small markers with the render thread saturated points at draw call submission. I also check whether the spike repeats every frame or only on a hitch, because a one-off hitch often comes from a hitch in asset streaming, shader compilation, or a GC pause rather than steady state cost.
In RenderDoc I capture that exact frame and read the event browser and GPU timeline. RenderDoc shows each draw event and its GPU duration. If one event, such as a shadow pass or a full-screen post process, accounts for most of the GPU time, that is the GPU cost to attack. If the GPU timeline shows long gaps between events, the GPU is waiting for the CPU to submit the next batch.
| Signal | CPU-bound | GPU-bound |
|---|---|---|
| CPU profiler | Main or render thread at or over 16.6 ms | CPU finishes with headroom, often under 10 ms |
| RenderDoc GPU timeline | Idle gaps between draw events | GPU busy for most of the frame interval |
| Halve the render resolution | Frame time barely moves | Frame time drops, especially for fragment-heavy passes |
| Longest RenderDoc event | No single event explains the spike | One or a few events dominate GPU time |
The resolution test is the quick sanity check I use in the interview and in the office. Lowering resolution reduces fragment work only. If the spike stays at 28 ms, fragment shading was not the cause. If it falls to 15 ms, it was.
Follow-up checks
For a CPU spike I drill into the marker that grew. Physics usually means broadphase, collision pairs, or too many bodies waking up. Animation usually means skeleton updates or bone matrix work for off-screen characters that should be culled. Render thread saturation usually means too many draw calls or state changes, which I confirm by counting events in RenderDoc.
For a GPU spike I check the dominant RenderDoc events for triangle count, overdraw, and expensive pipeline state. A shadow map re-rendered at full resolution, a post process chain running at full res, or a mesh with far more triangles than the screen needs will show up there. I also check for a fence wait in the CPU profiler. Repeated waits on the GPU fence mean the CPU is throttling itself to stay ahead of the GPU, which confirms GPU pressure even when CPU time looks low.
Two traps to avoid: RenderDoc captures add overhead, so I use it to find the culprit event and then confirm the fix in the CPU profiler without RenderDoc attached. And with vsync on, a GPU-bound frame can look capped at 16.6 ms, so I profile with vsync off when I need the raw cost.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7How would you pool bullets and particles so a 10,000-particle burst never allocates or fragments during a frame, and what do you do when the pool runs dry?
The 90-second answer
Preallocate one fixed array per type at load time, for example 128 bullets and 4,096 particles, and never allocate or grow anything during gameplay. A free list stores indices of dead slots. Spawning pops an index, despawning pushes it back. Both are O(1), the heap sees no variable-sized requests in the frame loop, and fragmentation cannot happen because the pool is a single allocation made before play starts.
Capacity and exhaustion policy are the real design decisions. Size from a recorded worst case, then add headroom. If a gun fires 10 bullets per second and a bullet lives 1.5 seconds, steady state is 15 live bullets. A burst weapon at 30 per second peaks at 45, so 128 covers two players plus a turret. Particles are harder: one explosion emits 300, three at once plus muzzle flashes can hold 2,000 live, and a boss death might emit 5,000. I test with the worst recording played back at double spawn rate. If it still exhausts, the design needs changing, not a bigger pool by guesswork.
Implementation
// C++17
#include <cassert>
struct Particle {
float x, y, vx, vy, life;
bool alive = false;
};
class ParticlePool {
static constexpr int CAPACITY = 4096;
Particle pool_[CAPACITY];
int freeList_[CAPACITY];
int freeCount_ = CAPACITY;
uint32_t generation_[CAPACITY] = {};
public:
ParticlePool() {
for (int i = 0; i < CAPACITY; ++i) freeList_[i] = CAPACITY - 1 - i;
}
int spawn(float x, float y, float vx, float vy, float life) {
if (freeCount_ == 0) return -1;
int idx = freeList_[--freeCount_];
pool_[idx] = {x, y, vx, vy, life, true};
return idx;
}
void despawn(int idx) {
assert(pool_[idx].alive); // catches double release in debug builds
if (!pool_[idx].alive) return;
pool_[idx].alive = false;
++generation_[idx];
freeList_[freeCount_++] = idx;
}
void update(float dt) {
for (int i = 0; i < CAPACITY; ++i) {
if (!pool_[i].alive) continue;
pool_[i].life -= dt;
if (pool_[i].life <= 0) { despawn(i); continue; }
pool_[i].x += pool_[i].vx * dt;
pool_[i].y += pool_[i].vy * dt;
}
}
};Bullets use the same pattern in a separate pool. Mixing types wastes memory and hurts cache locality when the renderer walks the array.
When the pool runs dry
Particles drop the new spawn. A slightly smaller explosion beats a hitch. Player bullets should not drop silently, because that reads as a bug, so I block the shot or recycle the oldest bullet. Enemy bullets recycle the oldest, which keeps pressure on the player. Recycling the oldest is an O(n) scan, but it only runs on exhaustion. I count every exhaustion event. If the counter fires in normal play, capacity is wrong.
Failure modes
Double despawn pushes the same index twice, so two systems end up owning one slot. The assert and the alive check catch it. Stale handles are subtler: a system stores an index, the particle dies, the slot is reused, and the old system now moves the new particle. Store (index, generation) as the handle and reject it when the generation differs. Bullets referenced by homing or collision code need this. Visual particles nothing references can skip it.
Spawning during update also bites. A particle spawned into a slot already passed skips this frame. One spawned into a slot ahead of the cursor updates once this frame, when the loop reaches it, which may be earlier than intended. I defer spawns through a queue processed after the update loop, or iterate a snapshot of live indices.
Verification
I run the stress scene with an allocation hook counting heap calls after warmup. The count must stay at zero for 10 minutes. I also check frame time: scanning 4,096 slots for 12 live particles wastes cache, so for particles I often pack live ones at the front with swap-remove and let the renderer walk a tight array. Bullets stay on a free list because they are few and often referenced by handle.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Walk me through using dot and cross products to test whether an enemy is in front of the player and to project movement onto a slope, and what breaks when vectors are nearly parallel?
The 90-second answer
Dot product measures alignment. For unit vectors a and b, a · b = cos(theta), where theta is the angle between them. That gives a cheap test for "in front": compare the dot of the player's forward vector with the direction to the target against a threshold. It also gives projection: the component of one vector along another is b * (a · b) when b is unit length.
Cross product gives a perpendicular axis. a x b is perpendicular to both inputs, with length |a||b|sin(theta). In gameplay I use it to get a side vector for strafing and turning, and to get the axis of rotation between two directions.
// C++17, vectors assumed normalised unless stated
bool inFrontOfPlayer(const Vec3& forward, const Vec3& toTarget, float cosThreshold) {
// forward and toTarget must be unit length. cos(60 deg) = 0.5
return dot(forward, toTarget) > cosThreshold;
}
Vec3 projectOntoPlane(const Vec3& v, const Vec3& planeNormal) {
// Remove the component along the normal. planeNormal must be unit length.
return v - planeNormal * dot(v, planeNormal);
}
Vec3 sideAxis(const Vec3& forward, const Vec3& up) {
Vec3 s = cross(forward, up);
float len = length(s);
if (len < 1e-6f) return Vec3::zero; // forward parallel to up, no stable side axis
return s / len;
}Worked trace: field of view check
Player forward is (0, 0, -1). An enemy is 10 m ahead and 10 m to the right, so the raw offset is (10, 0, -10). Normalise it to (0.707, 0, -0.707). The dot product is 0*0.707 + 0*0 + (-1)*(-0.707) = 0.707. That is cos(45 deg), so the enemy is 45 degrees off centre. With a 60 degree half angle threshold (cos = 0.5), 0.707 > 0.5 passes. An enemy directly to the right gives offset (1, 0, 0), dot 0, angle 90 degrees, and fails. No acos call is needed per candidate, which matters when you test 200 AI agents per frame. Compare the dot against a precomputed cosine.
If you forget to normalise toTarget, the test breaks in a distance dependent way. The same enemy at 20 m gives offset (20, 0, -20) and a dot of 20, which passes any threshold even if it is at 80 degrees. Normalise once, or divide by length, before comparing.
Projection onto a slope
A character moving with velocity v = (0, -2, -5) hits a ramp with unit normal n = (0, 0.866, 0.5). The normal component is dot(v, n) = -2*0.866 + -5*0.5 = -4.232. Subtracting it: v - n * (-4.232) = (0, -2 + 3.666, -5 + 2.116) = (0, 1.666, -2.884). The result lies in the ramp plane, so the character slides along the surface instead of sinking into it or bouncing. The same formula projects a shadow, a movement wish direction, or a knockback impulse onto a wall. If the normal is not unit length, scale the correction by dot(v, n) / dot(n, n) instead.
Cross product for turning
To decide whether to turn left or right toward a target, compute axis = cross(forward, toTarget). Its y component tells the sign in a right handed, y up system. Forward (0, 0, -1), target to the right (1, 0, 0): cross = (0*0 - (-1)*0, (-1)*1 - 0*0, 0*0 - 0*1) = (0, -1, 0). Negative y means turn right in this convention. The full cross vector, normalised, is also the rotation axis you would feed to a quaternion angleAxis or a turret yaw calculation. For a side vector, cross(forward, up) with up (0, 1, 0) gives (1, 0, 0) for the forward above, which is the strafe direction.
| Test | Dot product | Cross product |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Front or behind | Sign and magnitude of cos(theta) | No direct answer |
| Angle between vectors | acos(clamp(dot, -1, 1)) | `atan2( |
| Perpendicular axis | No | a x b, length falls to zero when parallel |
| Projection | b * dot(a, b) for unit b | No |
Failure modes I check in code
Parallel vectors make cross product length near zero. Looking straight up with forward parallel to world up is the classic case. Normalising that result divides by a tiny number and produces a jittering side axis. Guard with an epsilon and fall back to a stored last valid side vector or a different reference up.
Near zero length input vectors cause the same problem for dot tests. A target exactly at the player position has no direction. Skip the test or reuse the previous direction.
Floating point drift accumulates when you normalise by repeated multiplication. Renormalise forward vectors after integrating rotation each frame, and clamp the dot to [-1, 1] before calling acos, since 1.0000002 returns NaN.
Handedness flips the sign of the cross product. Mixing a left handed engine convention with a right handed formula inverts left and right turns. Pick one convention, document it next to the helper, and test it with the trace above in a unit test.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9How do you fix a character that moves faster diagonally, keep analog stick walk speed when you normalize, and stop a zero input from producing NaNs?
The 90-second answer
Velocity is direction times speed, and the result only has the speed you tuned if the direction has length 1. If dir has length L, dir * speed has length L * speed. The fix is not to normalize blindly everywhere. You normalize a pure direction, you clamp an analog input to length 1 while preserving smaller magnitudes, and you guard the zero case before you divide.
// C++17, Vec3 with length() and normalized()
Vec3 input{1.0f, 0.0f, 1.0f}; // both stick axes pushed, diagonal
float speed = 6.0f; // m/s
float len = input.length(); // 1.414
Vec3 dir = (len > 1.0f) ? input / len : input;
Vec3 velocity = dir * speed; // (4.24, 0, 4.24), length 6.0Without the clamp, velocity is (6, 0, 6), length 8.49. That is the diagonal boost: sqrt(2) times the cardinal speed, because (1, 1) has length sqrt(2).
Why always normalizing the stick is wrong
An analog stick encodes intent in its magnitude. A tilt of 0.3 should walk, a full tilt should sprint. If you call normalized() on every input, a 0.3 tilt becomes length 1 and the character runs at full speed. You have removed the analog control the designer built.
Clamping preserves both behaviours. Lengths above 1 are scaled down to 1, so diagonals and over-tilted sticks cannot exceed the tuned speed. Lengths below 1 pass through unchanged, so gentle tilts stay gentle.
| Input | Length | After clamp | Velocity at 6 m/s |
|---|---|---|---|
(1, 0) cardinal | 1.0 | (1, 0) | 6.0 m/s |
(1, 1) diagonal | 1.414 | (0.707, 0.707) | 6.0 m/s |
(0.3, 0) gentle tilt | 0.3 | (0.3, 0) | 1.8 m/s |
(0, 0) centred | 0.0 | (0, 0) | 0 m/s |
Trace the diagonal case through the code above. len is 1.414, the branch divides by it, and each axis becomes 0.707. Multiply by 6 and the character covers 4.24 m/s on each axis, 6.0 m/s along the diagonal. Trace the gentle tilt. len is 0.3, the branch is skipped, and velocity is 1.8 m/s. One branch handles both, and the walk speed survives.
The zero vector failure
Normalization divides by length. A centred stick, a seek target exactly at the character position, or a delta between two identical animation frames gives length 0. Dividing produces NaN or infinity, and that value then propagates into the transform, the physics body and the camera. The object disappears or teleports, and the NaN spreads to anything that reads its position.
Guard before you divide, and test length squared so the common path avoids an extra square root:
Vec3 safeNormalized(const Vec3& v) {
float lenSq = v.lengthSquared();
if (lenSq < 1e-8f) return Vec3::zero;
return v / std::sqrt(lenSq);
}The threshold matters. A length of 1e-5 is not a usable direction, it is floating point noise, and dividing by it amplifies that noise into a random full-speed direction. Returning zero means no input produces no movement, which is the behaviour a player expects.
Where you deliberately do not normalize
A displacement is not a direction. Root motion from an animation clip, a knockback impulse and a projectile step all carry distance in their length. Normalizing them discards the distance and replaces it with your constant speed, so a short hop and a long lunge move the same amount per frame. For those, keep the vector as is and let its length do its job. Normalize only when the length is meaningless and the direction is the data, such as a facing vector, a seek direction or a reflection normal.
Length also leaks into math that assumes unit inputs. dot(dir, normal) should return a cosine between -1 and 1. Feed in a vector of length 5 and it returns 5 times the cosine, so a wall check that should read 0.7 reads 3.5 and passes when it should fail. That is why the invariant belongs at the boundary where an untrusted vector enters gameplay code. Normalize or clamp there, once, and downstream code can rely on length 1 without rechecking.
The cost is one square root and one division per character per frame, which is negligible. It only becomes a concern per particle or per vertex, and there you normalize once in the asset or spawn data and reuse the stored unit vector.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Why would you use quaternions instead of Euler angles for character rotation, and how does gimbal lock happen?
The 90-second answer
For a character I store orientation as a quaternion, four numbers (x, y, z, w), and only convert to Euler angles for display or for a designer-facing inspector. Euler angles are three rotations applied in a fixed order, usually yaw, pitch, roll. That order is the problem. When pitch reaches plus or minus 90 degrees, the yaw axis and the roll axis point the same way. Two of the three angles then control the same physical rotation, so one degree of freedom is lost. That is gimbal lock.
A quaternion has no order and no singular pitch. It represents an axis and an angle in one object, so interpolation between two orientations stays on the shortest arc and never hits that alignment.
What gimbal lock looks like in practice
Take a character turning in a flight game, or a camera looking straight down. With Euler order YXZ (yaw, then pitch, then roll):
// Unity, checked against Unity 2022 LTS
transform.rotation = Quaternion.Euler(pitch, yaw, roll);Trace with pitch fixed at 90 degrees:
| yaw | pitch | roll | Resulting orientation |
|---|---|---|---|
| 0 | 90 | 0 | Facing down, nose along -Z |
| 30 | 90 | 0 | Facing down, rotated 30 degrees about the world vertical |
| 30 | 90 | 40 | Identical to yaw 70, pitch 90, roll 0 |
The last two rows are the tell. Changing roll by 40 degrees did exactly what changing yaw by 40 degrees would have done. The controller can no longer command roll independently. If gameplay code increments roll to bank the character while the camera is pitched down, the character yaws instead, or appears to ignore the input entirely. The same loss happens at pitch -90 degrees, with the axes aligned in the opposite sense.
This is not a floating point error that a larger epsilon fixes. At exactly 90 degrees the rotation matrix loses rank for that parameterisation. Near 90 degrees it is almost as bad: small changes in pitch produce large, coupled swings in yaw and roll, which is why Euler-driven cameras often snap or spin when the player looks almost straight up.
Why quaternions avoid it, and what they cost
A unit quaternion q = (axis * sin(theta/2), cos(theta/2)) encodes the rotation directly. Composition is quaternion multiplication, and there is no intermediate axis to align with another. Slerp, spherical linear interpolation, blends between two orientations at constant angular speed:
Quaternion a = Quaternion.Euler(90f, 30f, 0f); // convert once, at authoring time
Quaternion b = Quaternion.Euler(90f, 30f, 40f);
Quaternion mid = Quaternion.Slerp(a, b, 0.5f); // well defined, no snap
transform.rotation = mid;| Property | Euler angles (3 floats) | Quaternion (4 floats) |
|---|---|---|
| Storage | 12 bytes | 16 bytes |
| Gimbal lock | Yes, at pitch +/-90 degrees for YXZ | No singular orientation |
| Interpolation | Naïve lerp takes the long way and can flip | Slerp follows the shortest arc at constant speed |
| Composition | Order dependent, easy to get wrong | Multiplication, order still matters but no singularity |
| Human editing | Intuitive for yaw/pitch/roll sliders | Opaque, needs tooling |
| Failure mode | Lost degree of freedom, coupled axes | Must stay normalised, q and -q are the same rotation |
The costs are real but manageable. A quaternion must stay unit length. Repeated multiplication drifts it, so normalise after composing in hot loops, or renormalise periodically. And q and -q describe the same orientation, which breaks naïve component-wise lerp and equality checks. Slerp handles the sign internally, and if you compare orientations, compare the resulting forward vector or use Quaternion.Angle, not the raw components.
When I would still use Euler angles
For a turret that only yaws, a door that only rotates on one hinge, or a designer tool where someone drags a yaw slider. Single axis rotation cannot lock. I also keep Euler angles at the boundary: read them from a level editor, convert once with Quaternion.Euler, simulate in quaternions, and convert back only for the inspector. The mistake is simulating frame to frame in Euler angles, accumulating yaw and roll independently while pitch sits near vertical. That is where the character starts misbehaving in a way that looks like a bug in the input code, when it is the representation.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Your moving platform scales, rotates and translates each frame, but riders drift and the deck shears. How do you compose its transform matrix and prove the order is correct?
The 90-second answer
State the convention first, because the order is meaningless without it. I will use column vectors, right-handed, as in OpenGL and glm: a point is transformed as p' = M * p, and the rightmost matrix acts first. For a platform with local scale S, local rotation R and world translation T, the model matrix is:
M = T * R * SThat reads inside out. A deck corner is scaled in platform space, then rotated about the platform origin, then moved to its world position. If you write S * R * T, or R * T * S, you have not just a different convention, you have a different object. Translation ends up rotated or scaled, and non-uniform scale ends up applied along world axes instead of the deck's own axes, which is the shear riders feel.
The test is not "does it look roughly right". I check three things: where the basis vectors land, where a known corner lands, and what happens to a rider when the platform moves.
Worked trace
Take a 2D version for clarity, same maths in 3D. Platform half-extents are scaled by S = scale(2, 1), rotated 90 degrees, R = rotZ(90°), then translated by T = translate(10, 0). Corner p = (1, 1) in local space.
| Step | Operation | Result |
|---|---|---|
| 1 | S * p | (2, 1) |
| 2 | R * (2, 1) | (-1, 2) |
| 3 | T * (-1, 2) | (9, 2) |
So M * p = (9, 2). Now the common wrong order, S * R * T * p: translate gives (11, 1), rotate gives (-1, 11), scale gives (-2, 11). The platform is 11 units up instead of 2, and its long axis now points the wrong way. A second wrong order, R * S * T, puts the translation through the rotation, so the platform orbits the origin instead of travelling to (10, 0). Both errors are obvious in the trace and invisible if you only eyeball a symmetric, unscaled platform in a test scene.
In code, with glm column-major:
// Checked against glm 1.0, column vectors: M * v
mat4 S = scale(vec3(2.0f, 1.0f, 1.0f));
mat4 R = rotate(mat4(1.0f), radians(90.0f), vec3(0, 0, 1));
mat4 T = translate(mat4(1.0f), vec3(10.0f, 0.0f, 0.0f));
mat4 M = T * R * S;
vec3 corner = M * vec3(1.0f, 1.0f, 0.0f); // (9, 2, 0)
// Basis check: local X axis must map to R * (1,0,0) scaled, not to a world axis
vec3 xAxis = normalize(M * vec4(1, 0, 0, 0)); // (0, 1, 0) after 90 deg rotationWhy non-uniform scale is the trap
With uniform scale the wrong order often passes a casual test, because scaling commutes with rotation up to a scalar. With S = scale(2, 1, 1) it does not. R * S scales along the platform's local axes and then turns the result, so the long axis stays aligned with the deck. S * R rotates first and then stretches along world X, so a deck rotated 45 degrees gets longer along world X and its corners shear relative to the rider's footing. The deck looks like a parallelogram, its inverse matrix no longer matches the visual, and physics and rendering disagree about where the edge is. That mismatch, not the visual alone, is what makes riders slide off an edge the renderer drew somewhere else.
Normals need the inverse transpose, transpose(inverse(M)), when scale is non-uniform. Using M directly for normals skews lighting on the deck even when positions are correct, which is a useful diagnostic: correct corners plus wrong lighting usually means the normal matrix, not the model matrix, is wrong.
Riders and the moving platform failure mode
The subtler bug is cumulative. Do not transform a standing rider by the full M every frame. Store the rider in platform-local space, or compute the frame delta:
mat4 delta = M_current * inverse(M_previous);
vec3 riderWorld = delta * vec4(riderWorld, 1.0f);That carries the rider through the platform's rotation and translation for this frame only. If you instead reapply M_current to an already world-space rider, the rider gains the platform's translation again each frame and accelerates away, which looks like sliding. If the platform rotates under a rider kept in world space with no delta, the rider stays put while the deck turns, so feet slide in an arc. The delta approach also gives you the platform velocity for free: (delta * riderPos - riderPos) / dt, which you need for jumping off a moving platform without inheriting a stale velocity.
My test scene therefore has three assertions, not one screenshot: a scaled corner lands at the hand-computed (9, 2), the deck's local X basis is perpendicular to its local Y basis after the transform when scale is uniform, and a rider placed at local (0.5, 0) stays at that local coordinate after 60 frames of rotation. Fail any of those and the order, or the rider handling, is wrong, even if the platform renders a plausible shape.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12For a rotated vehicle, why does an AABB produce false collisions while an OBB does not, and when would you use a sphere instead for a projectile?
The 90-second answer
For a rotated vehicle I would use an OBB for the narrowphase and keep an AABB only as a cheap broadphase proxy. An AABB cannot rotate, so as the vehicle turns its box has to grow to contain the corners. That growth creates collisions where the mesh is not. An OBB stores a centre and a rotation, so its box turns with the vehicle and stays tight. For a projectile I would use a sphere, because it is small, roughly round, and its test does not depend on orientation at all.
| Shape | What it stores | Test cost | Problem when rotated |
|---|---|---|---|
| Sphere | Centre, radius | Distance check | None, but loose for elongated objects |
| AABB | Min and max on world axes | 6 comparisons | Must grow to contain rotated corners |
| OBB | Centre, rotation matrix | Separating Axis Test, up to 15 axes | None, but most expensive |
Why the AABB fails on the vehicle
Take a vehicle 4.4 m long and 1.9 m wide. Axis aligned, its AABB is exactly 4.4 by 1.9 m, area 8.36 m2. Turn it 45 degrees and the world axis extents become (4.4 + 1.9) / sqrt(2) = 4.45 m on both axes. The AABB is now 4.45 by 4.45 m, area 19.8 m2. More than double the true footprint, and most of that extra area is empty corners. In a doorway 3 m wide the car visually fits, but the AABB reports a hit on both sides and the car stops a metre early. Players read that as a bug, not as physics.
An OBB avoids it by rotating its local axes with the vehicle. Its extents stay 4.4 by 1.9 m at any heading, so the test only reports contact where the body actually is. The price is the test itself. Two OBBs need the Separating Axis Test over 15 axes, the 3 face normals from each box plus 9 cross products of their edges. That is still cheap for a handful of vehicles, which is why I accept it there and not for hundreds of debris objects.
// AABB overlap, C++17. boxMin/boxMax are world-space.
bool AABBOverlap(const Vec3& aMin, const Vec3& aMax,
const Vec3& bMin, const Vec3& bMax) {
return aMin.x <= bMax.x && aMax.x >= bMin.x &&
aMin.y <= bMax.y && aMax.y >= bMin.y &&
aMin.z <= bMax.z && aMax.z >= bMin.z;
}For the OBB version I transform the other object into the vehicle local space with the inverse rotation, then run the same axis checks there. If the boxes are separated on any local axis, they do not collide.
Why a sphere for the projectile
A projectile is small and its orientation rarely matters to gameplay. A sphere test is one distance check, it needs no rotation data, and it behaves the same at every angle. The trade-off is fit. A sphere around a long spear would need a radius covering its length and would snag on frames it should pass through. For a bullet or fireball that cost does not arise, so the sphere wins on simplicity and speed.
In practice I layer them. Spheres or AABBs run first as broadphase to reject distant pairs. The OBB test runs only for pairs that pass, which keeps the expensive test off the hot path for most objects.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13With 5,000 dynamic objects in a 2D arena, how would you use a quadtree to cut collision pairs, and when would you switch to an octree or a uniform grid instead?
The 90-second answer
Assume a 2D top-down game, 5,000 dynamic objects with axis-aligned bounding boxes, and collision only between objects that overlap. The naive check is the problem: 5,000 x 4,999 / 2 = 12.5 million pairs per frame. At 60 fps that is 750 million narrow-phase tests a second, before any physics runs. A quadtree does not make collision cheaper. It makes most pairs never get tested.
The root covers the arena. Each node splits into four quadrants when it holds more than, say, 16 objects, and objects are stored in the smallest node that fully contains them. To find candidates for one object, you walk the leaf it sits in plus its ancestors and neighbours, and test only objects found there. In a spread-out arena that is typically tens of candidates, not thousands.
Worked trace
Arena 0..1024 on both axes, capacity 4, max depth 5. Insert a projectile at (900, 100) with a 8x8 box. It lands in the top-right quadrant, that quadrant splits, and the projectile ends in a leaf covering 896..1024, 0..128. Querying it visits that leaf and the adjacent leaves sharing an edge, because its box can cross a border. It never visits the bottom-left quadrant. If 200 enemies are clustered in the bottom-left, they are never compared against this projectile. That locality is the whole win.
// Checked against C++17. Objects stored by index into a flat array.
struct Node {
Rect bounds;
std::vector<int> ids; // objects fully inside this node
std::unique_ptr<Node> child[4];
bool leaf() const { return child[0] == nullptr; }
};
void insert(Node& n, int id, const Rect& r) {
if (n.leaf() && n.ids.size() < 16) { n.ids.push_back(id); return; }
if (n.leaf()) split(n);
for (auto& c : n.child)
if (contains(c->bounds, r)) { insert(*c, id, r); return; }
n.ids.push_back(id); // straddles a split line: keep at this level
}
void queryPairs(Node& n, const Rect& r, int self, std::vector<int>& out) {
for (int id : n.ids) if (id > self && overlaps(r, objects[id].box)) out.push_back(id);
if (n.leaf()) return;
for (auto& c : n.child)
if (overlaps(c->bounds, r)) queryPairs(*c, r, self, out);
}The id > self guard emits each pair once. The straddle case matters: an object crossing a quadrant boundary cannot go into one child, so it stays at the parent. Every query that reaches that parent sees it.
Dynamic objects and rebuild cost
Moving objects cross leaf boundaries constantly. Two workable policies: remove and reinsert only when the centre leaves the current leaf, which is cheap but leaves the tree unbalanced over time, or rebuild the whole tree each frame. Rebuilding 5,000 inserts is usually fine, roughly 5,000 x depth pointer hops, and it keeps the tree balanced. I rebuild when the count is in the low thousands and the frame budget allows it, and I switch to incremental updates when profiling shows rebuild dominating. Either way, I count pair tests per frame. If that number climbs while object count stays flat, the tree is degrading.
Choosing the structure
| Structure | Best when | Weakness |
|---|---|---|
| Quadtree | 2D, uneven density, mixed object sizes | Large straddling objects pile up at the root |
| Octree | Same idea in 3D, 8 children per split | Deeper trees, more nodes, worse cache behaviour than 2D |
| Uniform grid | Roughly even density, mostly similar sizes | One dense cluster overloads a single cell |
| Sweep and prune | Mostly sorted along one axis, few overlaps | Fails when objects move a lot on that axis |
An octree is the direct 3D analogue: split a cube into eight, same insert and query logic, one more level of depth for the same resolution. I would pick it for a 3D shooter with thousands of debris pieces and pickups. I would pick a uniform grid instead if the level is a flat arena with even density, because a flat array of cells beats pointer chasing through nodes.
Failure modes I watch for
A level trigger covering the whole map straddles every split, so it lives at the root and gets tested against every query. That silently turns the tree back into a linear scan. Fix: keep a separate short list of large or static volumes and test them explicitly, or use a loose quadtree where a node stores objects whose centre falls inside an expanded bounds.
A second failure is clustering. If 4,000 objects spawn in one corner, that branch goes to max depth and each query there walks a long chain. The depth cap bounds the damage, and the pair count metric above exposes it. A third is stale entries after a remove-and-reinsert bug, which shows up as phantom collisions. I assert in debug builds that an id appears in exactly one leaf.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14What does broadphase collision check, and why does it run before narrowphase in the physics step?
The 90-second answer
Broadphase runs first. It checks cheap bounding volumes, usually AABBs, and discards every pair that cannot be touching. Narrowphase runs second, only on the pairs that survive, and does the exact shape test. Both run inside the physics step, after bodies are integrated and before the solver and render.
The rule to remember is cheap test first, expensive test second. Broadphase is allowed to be approximate. It may keep a pair that is not really touching. It must never discard a pair that is touching, because narrowphase will never see it.
What each stage checks
| Stage | Check | Result |
|---|---|---|
| Broadphase | Do the two AABBs overlap on the x, y and z axes? | Candidate pair, or rejected |
| Narrowphase | Do the exact shapes touch, for example sphere against sphere or box against mesh? | Contact point, normal and depth, or no contact |
An AABB is just a box aligned to the world axes, stored as a minimum corner and a maximum corner. Overlap on all three axes is six comparisons. That is why it can run on thousands of objects. The exact test for a rotated box against a triangle mesh can cost hundreds of operations, so it only runs on the small candidate list.
Worked trace
Suppose a level has 2,000 dynamic objects. Testing every pair would mean 2,000 x 1,999 / 2 = 1,999,000 pairs. Broadphase with sweep and prune sorts the AABBs on one axis and rejects most pairs without a full test. Say 1,500 pairs pass the AABB overlap on all three axes. Narrowphase then runs 1,500 times, not two million times. If 120 of those pairs are real contacts, the solver receives 120 manifolds. The numbers here are illustrative, but the ratio is the point. Broadphase turns an unusable pair count into a manageable one.
// Broadphase test: overlap on all three axes
bool Overlaps(const AABB& a, const AABB& b) {
return a.min.x <= b.max.x && b.min.x <= a.max.x &&
a.min.y <= b.max.y && b.min.y <= a.max.y &&
a.min.z <= b.max.z && b.min.z <= a.max.z;
}
// Order inside one physics step
void PhysicsStep(float dt) {
Integrate(dt); // update positions and AABBs
broadphase.BuildPairs(); // cheap AABB test, builds candidate list
for (Pair p : broadphase.Pairs())
if (narrowphase.Test(p.a, p.b)) // exact test, only on candidates
solver.AddContact(p);
solver.Solve(dt);
}Where it sits in the frame
Input and game update come first, then physics, then render. Inside physics the order is integrate, broadphase, narrowphase, solve. Broadphase needs the new positions, so it cannot run before integration. The solver needs the contact data from narrowphase, so it runs after. Render draws the state after the solve, which is why a resting prop appears settled rather than sinking into the floor by the penetration the solver just removed.
If broadphase used last frame's AABBs, a fast projectile could be missed for one step and tunnel through a thin wall. That is a stale data bug, not a narrowphase bug, and it is fixed by rebuilding the AABBs after integration and before the pair test.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Walk me through how you would implement a fixed-timestep physics loop with an accumulator, and how you would stop a fast projectile tunnelling through thin geometry at variable frame rates?
The 90-second answer
I would run physics at a fixed rate, 60 Hz in this example, and decouple it from rendering with an accumulator. Rendering can run at 144 Hz or dip to 30 Hz, but every physics step advances the simulation by exactly dt = 1/60 seconds. That gives deterministic integration, stable collision response, and a solver that behaves the same on every machine. Variable delta time breaks that: at 30 fps a body moves twice as far per step as at 60 fps, so a spring, a stack, or a fast projectile behaves differently depending on frame rate.
The accumulator loop, checked against C++17:
constexpr double kPhysicsDt = 1.0 / 60.0;
constexpr double kMaxFrame = 0.25; // clamp, see spiral of death below
double accumulator = 0.0;
double frameTime = clock.frameDelta(); // seconds since last render
frameTime = std::min(frameTime, kMaxFrame);
accumulator += frameTime;
while (accumulator >= kPhysicsDt) {
physics.step(kPhysicsDt);
accumulator -= kPhysicsDt;
}
double alpha = accumulator / kPhysicsDt; // 0..1, for render interpolation
render(interpolate(previousState, currentState, alpha));Interpolation matters. Without it, at 144 Hz rendering you would draw the same physics state two or three times, then jump. Store the transform before the last step and blend toward the current one by alpha.
Worked trace
Assume a hitch: frame times of 8 ms, 8 ms, 50 ms, 8 ms. Physics dt is 16.67 ms.
| Render frame | Frame time | Accumulator before steps | Physics steps run | Alpha after |
|---|---|---|---|---|
| 1 | 8 ms | 8 ms | 0 | 0.48 |
| 2 | 8 ms | 16 ms | 0 | 0.96 |
| 3 | 8 ms | 24 ms | 1 | 0.44 |
| 4 | 50 ms | 57.4 ms | 3 | 0.44 |
Frame 4 runs three steps to catch up. That catch-up is the failure mode to control. If a load takes 500 ms, the loop would try to run 30 steps, which makes the next frame later, which triggers more steps. That is the spiral of death. Clamping frameTime to 250 ms caps catch-up at 15 steps, and clamping to 100 ms caps it at 6. The cost is slow motion during the hitch, which is preferable to a freeze. I would also drop the accumulator remainder if it exceeds a few steps, rather than carrying debt forever.
Tunnelling through thin geometry
Fixed timestep alone does not fix tunnelling. Take a projectile at 30 m/s and a wall 0.1 m thick. In one 16.67 ms step it travels 0.5 m. A discrete overlap test at the start and end positions can miss the wall entirely, because neither endpoint is inside it. At a variable 33 ms frame it travels 1 m and the problem gets worse.
Three defences, in order of preference:
| Defence | How it works | Cost and limit |
|---|---|---|
| Substepping | Split the step, for example 4 substeps of 4.17 ms, so travel per substep is 0.125 m | Cheap to implement, still fails if speed rises or the wall gets thinner. 0.125 m still exceeds 0.1 m here. |
| Swept collision, CCD | Test the segment swept from previous to new position against the collider, and report time of impact | More expensive per pair, so apply it only to fast, small bodies. This is what Box2D bullet mode and PhysX CCD do. |
| Thicken or fatten the collider | Grow the wall or add a margin so discrete overlap catches it | Changes gameplay geometry and can snag slow objects on edges. Use only for invisible gameplay walls. |
In practice I combine them: swept tests for projectiles and other bodies flagged as fast, substepping for the character controller where continuous movement matters, and a sanity check in tests that speed times dt stays below the thinnest collider the body must hit. If that inequality cannot hold, the design needs CCD, not a smaller dt.
Two failure modes I would test explicitly. First, a body resting on a thin floor at low frame rate: with variable dt it can sink or bounce depending on frame time, with fixed dt plus interpolation it stays put. Second, a projectile fired point blank: swept collision must handle the case where the start position already overlaps, otherwise the time of impact calculation returns a negative value and the shot passes through. I would log time of impact, penetration depth, and steps per frame in a debug build, because tunnelling bugs are almost invisible in a single playthrough and obvious in that trace.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Your physics runs at a fixed 60 Hz but the display refreshes at 144 Hz. How do you decouple update from render with interpolation so motion stays smooth, and what breaks if you just render the latest physics state?
The 90-second answer
Run physics on a fixed step, say 1/60 s, and accumulate real elapsed time. Each frame, step physics zero or more times to consume that time, keeping the state before the last step and the state after it. Render is then a blend between those two states, weighted by how far the accumulator sits between ticks. The display can refresh at 144 Hz while the simulation stays deterministic at 60 Hz, and the rendered position moves every display frame instead of repeating the same physics pose two or three times and then jumping.
Without that blend, a 60 Hz simulation on a 144 Hz screen shows each pose for 2 or 3 refreshes. Motion looks steppy even though the simulation is correct, and the judder gets worse when the two rates drift against each other.
The loop
// Checked against C++17 style pseudocode, no engine dependency
constexpr float FIXED_DT = 1.0f / 60.0f;
float accumulator = 0.0f;
struct Body {
Vec3 prevPos; // state before the most recent physics step
Vec3 currPos; // state after the most recent physics step
Quaternion prevRot, currRot;
};
void frame(float realDt) {
accumulator += std::min(realDt, 0.25f); // clamp, see spiral of death below
int steps = 0;
while (accumulator >= FIXED_DT && steps < 5) {
for (Body& b : bodies) b.prevPos = b.currPos;
physicsStep(FIXED_DT);
accumulator -= FIXED_DT;
++steps;
}
if (steps == 0) {
// No step ran: prev and curr are still the last pair, alpha grows.
}
float alpha = accumulator / FIXED_DT; // 0..1, fraction toward the next tick
for (Body& b : bodies) {
Vec3 renderPos = b.prevPos + (b.currPos - b.prevPos) * alpha;
Quaternion renderRot = slerp(b.prevRot, b.currRot, alpha);
draw(b.mesh, renderPos, renderRot);
}
}Two details matter. First, prev must be copied before the step, not after, or the blend collapses to the current state. Second, rotation needs slerp on quaternions. Linearly interpolating quaternion components and renormalising bends the rotation path and can visibly speed up or slow down mid-turn.
Worked trace
A body moves at 6 m/s, so it advances 0.1 m per 16.67 ms tick. Display refreshes every 6.94 ms (144 Hz).
| Real time (ms) | Physics state | Alpha | Rendered x (m) | Without interpolation |
|---|---|---|---|---|
| 0.0 | tick 0, x = 0.0 | 0.00 | 0.00 | 0.0 |
| 6.9 | still tick 0 | 0.42 | 0.04 | 0.0 |
| 13.9 | still tick 0 | 0.83 | 0.08 | 0.0 |
| 20.8 | tick 1, x = 0.1 | 0.25 | 0.13 | 0.1 |
| 27.8 | tick 1 | 0.67 | 0.17 | 0.1 |
| 34.7 | tick 2, x = 0.2 | 0.08 | 0.21 | 0.2 |
Rendered x advances in small increments each refresh. The right-hand column holds, holds, then jumps 0.1 m at once. That jump is the judder players describe as stutter, and it appears even at a steady frame rate.
physics: |---tick0---|---tick1---|---tick2---|
render: ^ ^ ^ ^ ^ ^
alpha grows, then resets at each tickFailure modes and trade-offs
Spiral of death: if a hitch makes realDt 200 ms, the loop owes 12 steps. Running all of them makes the next frame later still, so the debt grows. Clamp realDt (0.25 s above) and cap steps per frame (5). When the cap hits, drop the remaining accumulator time. The simulation slows briefly instead of locking up. Dropping time is a visible slowdown, which is preferable to a freeze, and it should be rare enough to log.
Teleports and spawns: interpolation assumes small movement between ticks. A respawn from x = 0 to x = 100 would smear across the map for one tick. Mark such bodies as non-interpolated for one frame, setting prevPos = currPos on teleport, spawn and hard snap.
Latency: interpolation renders the world as it was partway between the last two ticks, so it adds up to one tick of visual latency (16.7 ms at 60 Hz) compared with rendering the newest state. Extrapolation avoids that by predicting ahead of the last tick, but it overshoots on collisions and direction changes. For player-controlled characters, many engines interpolate other entities and render the local player from the freshest state, accepting a small mismatch to keep input feeling responsive.
Variable-rate objects: particle systems, camera shake and UI animation do not need fixed steps. Interpolating them adds nothing and can hide their intended motion. Keep them on render dt, and only interpolate bodies whose state physics owns.
Determinism note: fixed dt is what makes replays and lockstep netcode possible, because the same inputs produce the same steps. Interpolation is purely presentational and never feeds back into physics. If rendered positions leak into collision or gameplay logic, determinism breaks and the blend starts affecting the simulation it was meant to follow.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Walk me through how const correctness on your gameplay APIs stops a read-only query from accidentally mutating game state, and where it stops helping?
The 90-second answer
Const correctness makes read-only intent part of the type, so the compiler rejects mutation through an API that promises not to mutate. A query such as FindNearestEnemy takes const World& and is itself const, so inside it you cannot call world.Spawn(...), sort world.entities_ in place, or assign to a member. If you try, compilation fails at that call site, not at runtime during a playtest when the AI has quietly reordered the entity list.
// C++17
class Player {
public:
float Health() const { return health_; } // read only
const Vec3& Position() const { return pos_; } // read only view
Vec3& Position() { return pos_; } // explicit write access
void Damage(float amount) { health_ -= amount; } // mutating
private:
float health_ = 100.0f;
Vec3 pos_{};
};
float DistanceTo(const Player& a, const Player& b); // cannot mutate a or b
void ApplyDamage(Player& p, float amount); // may mutate p
const Player* FindNearestEnemy(const World& world, Vec3 from) {
const Player* best = nullptr;
for (const Player& p : world.Players()) {
// p.Damage(10.0f); // compile error: p is const Player&
// world.Spawn(...); // compile error: world is const, method is non-const
if (!best || DistanceTo(p, /*...*/)) best = &p;
}
return best;
}The compiler error is the point. It names the exact line where a supposedly read-only path tried to write, while the code is still cheap to fix.
How the mechanism works
A const member function receives this as const Player*. Every member access through it yields a const lvalue, so health_ = 50.0f inside Health() const is rejected. A non-const overload can coexist, as with Position() above. Overload resolution picks the const version when the object is const and the non-const version when it is mutable, which gives callers a clear read path and write path.
For parameters, top-level const on a by-value argument does nothing for the caller: void Damage(const float amount) still copies. The useful form is const Player& or const Player*, which blocks mutation through that reference or pointer while allowing reads and calls to const methods. Passing a mutable Player to DistanceTo is fine, because a mutable object binds to a const reference. The reverse fails, which is exactly the protection you want when a helper should never change its inputs.
Pointer constness has three distinct positions, and mixing them up is a common source of bugs:
| Declaration | Can reseat pointer? | Can mutate pointee? |
|---|---|---|
Player* p | yes | yes |
Player* const p | no | yes |
const Player* p | yes | no |
const Player* const p | no | no |
In gameplay code I use const Player* const for a cached target inside a tick function: the target cannot be swapped mid-loop and the code cannot damage it through that handle.
Where it stops helping
Const is shallow and voluntary. It does not freeze the object in memory, and it does not make concurrent access safe. Three escape hatches need discipline:
const_castremoves const, so a stray cast defeats the check entirely. I treat it as a code review flag.mutablemembers can change inside a const method. That is legitimate for a lazy cache, such as a cached distance field recomputed on demand, but amutablehealth value would be a lie.- A const object holding a pointer can still mutate the pointee:
const Worldwith aPlayer* raw_member can callraw_->Damage(...)because the pointer itself is const, not its target. ReturningVec3&from a const method has the same effect, which is why the read accessor above returnsconst Vec3&.
There is also logical constness. A method can be const-correct at the type level and still change observable game state through a global, a singleton, or an audio system. Const correctness narrows the accidental-mutation surface to those explicit channels, where it can be reviewed. Used that way, it turns a class of intermittent gameplay bugs, where a query function nudges state, into compile errors at the moment the code is written.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18When would you pass a function parameter by reference instead of by pointer in C++, and what does that say about nullability and reseating?
The 90-second answer
Use a reference when the parameter must exist. Use a pointer when it may not, or when the function needs to change which object it refers to. That one rule decides most cases in game code.
void Move(const Vec3& target); // target must exist, cannot reseat
void SetTarget(Vec3* target); // target may be null, can reseatA reference is an alias for an existing object. It binds once at the call site and cannot be rebound inside the function. A pointer is a variable holding an address. It can be null and it can be reassigned.
What that means in practice
| Property | const T& | T* |
|---|---|---|
| Nullability | No null state in the contract. The caller must pass a real object. | nullptr is a valid, explicit state. |
| Reseating | Impossible. ref = other; assigns to the referred object, it does not change the binding. | ptr = &other; changes which object is referred to. |
| Syntax at call site | Move(pos); | SetTarget(&pos); or SetTarget(nullptr); |
| Syntax inside | target.x | target->x, with a null check first |
| Default choice | Preferred for a required input, especially large or non-copyable types. | Preferred for optional input, ownership transfer, or when reseating is needed. |
For a per-frame update, void Update(const Transform& parent, float dt) says the parent is mandatory. The compiler enforces a real argument at the call site and the reader does not hunt for a null check. void AttachTo(Entity* parent) says the entity may be detached. Passing nullptr there is meaningful, not a bug.
Reseating, concretely
Vec3 a{1, 0, 0}, b{0, 1, 0};
const Vec3& ref = a;
ref = b; // a becomes {0, 1, 0}. ref still refers to a.
// ref = b; cannot make ref refer to b.
Vec3* ptr = &a;
ptr = &b; // ptr now refers to b. a is unchanged.
ptr = nullptr; // valid for a pointer, meaningless for a referenceThat assignment trap is the classic interview follow-up. With a reference, = copies the value into the original object. With a pointer, = copies the address.
Failure modes
A reference can still be made to dangle, and it can be bound to null through a dereference, but both break the contract rather than using a supported state:
Vec3* maybe = FindSpawnPoint(); // may return nullptr
Move(*maybe); // undefined behaviour if null. The reference looks safe and is not.The pointer version forces the check into the open: if (maybe) Move(*maybe);. That is why optional parameters should be pointers, or better, std::optional<std::reference_wrapper<T>> in modern C++ when you want the nullability without raw pointer syntax.
Dangling is shared by both. A reference or pointer to a destroyed entity, a moved-from object, or a temporary whose lifetime has ended will compile and crash later. References do not protect against lifetime bugs. They only remove the null case and the reseat case.
When not to use a reference
Do not use one for output parameters that need to signal failure, for a parameter the function must rebind, or for an optional argument. Use a pointer there, or return a value. Do not use a raw pointer for a required large argument either. const T& avoids the copy, avoids the null check, and makes the requirement visible in the signature, which is why it is the default for read-only game data such as transforms, materials, and input state.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19Walk me through what happens when you push to a std::vector while iterating it, and how growth, reserve, and invalidation change the outcome?
The 90-second answer
A std::vector is one contiguous allocation. size() is how many elements are live, capacity() is how many fit in that allocation. push_back writes at begin() + size() if there is room. If size() == capacity(), it allocates a new, larger block, moves every element across, frees the old block, and only then appends. That move is the invalidation point. Every iterator, reference, and pointer into the old block dangles, because the elements no longer live there.
Pushing during iteration therefore has two separate hazards. The first is reallocation. The second happens even with no reallocation: end() moves, so a loop written as for (auto it = v.begin(); it != v.end(); ++it) will visit the newly pushed elements. If spawning projectiles spawns more projectiles, that loop never terminates.
// Buggy: spawns during update
for (auto it = projectiles.begin(); it != projectiles.end(); ++it) {
if (it->dead) SpawnDebris(*it); // push_back inside
it->Update(dt); // UB if reallocation moved *it
}If SpawnDebris triggers growth, it points into freed memory on the next line. In a debug build with checked iterators this may assert. In a release build it reads freed heap, which can look correct for hours until the allocator reuses that block for something else.
Growth arithmetic
The growth factor is not in the standard. libstdc++ doubles capacity, MSVC grows by 1.5x. The standard only guarantees geometric growth, which keeps amortized push_back at O(1). Take a hypothetical 1,000 entity spawn with doubling from capacity 1:
| Strategy | Allocations | Element moves (approx.) |
|---|---|---|
| No reserve, doubling | 10 (1, 2, 4, ..., 512, 1024) | 1,023 |
reserve(1024) first | 1 | 0 |
| No reserve, 1.5x growth | about 17 | about 2,000 |
That is why a burst of 10,000 particles allocated mid-frame shows up as a hitch. The cost is not one allocation, it is repeated copying plus allocator contention, and the largest copy happens at the worst moment, when the vector is already big.
reserve(n) sets capacity to at least n and performs at most one reallocation. It does not change size(). Calling reserve(1024) on an empty vector gives you room for 1,024 pushes with no invalidation from growth. It does not fix the logical problem above. References stay valid while capacity holds, but end() still advances.
What invalidates what
| Operation | Iterators | References / pointers |
|---|---|---|
push_back with spare capacity | end() invalidated, others stay valid | Stay valid |
push_back causing reallocation | All invalidated | All invalidated |
insert / erase in the middle | Invalidated from the point of change onward | Invalidated from that point onward |
erase at the end, pop_back | Only end() | Unaffected for remaining elements |
clear() | All invalidated | All invalidated |
reserve() causing reallocation | All invalidated | All invalidated |
Note the middle row for push_back with spare capacity. Code that caches auto end = v.end(); before the loop and iterates to that cached end will miss new elements, which is sometimes exactly what you want for a spawn pass. Code that re-reads v.end() each iteration will include them. Both compile. Only one matches the design intent.
How I write it in game code
For an entity list I update in place, I reserve for the known maximum at level load, iterate by index over a size snapshot, and queue spawns for after the loop:
projectiles.reserve(2048);
const size_t count = projectiles.size();
for (size_t i = 0; i < count; ++i) {
projectiles[i].Update(dt);
if (projectiles[i].dead) pendingSpawns.push_back(projectiles[i].debris);
}
// apply removals (swap-remove backwards) and pendingSpawns hereIndexing avoids holding an iterator across a mutation. The snapshot stops newly spawned items from being updated in the same pass, which also stops a chain reaction where a debris particle spawns its own debris in one frame. Swap-remove backwards keeps removal O(1) per element and does not shift the tail.
When I genuinely need to grow during iteration, for example merging two lists, I reserve a.size() + b.size() before the loop and re-acquire iterators after any push that might reallocate. In practice I prefer the deferred queue. It makes the frame's mutation order explicit, it keeps the update loop free of reallocation surprises, and it gives the pool or allocator a chance to batch the spawns.
The failure mode to watch for in review is a reference held across a call that can push. const Entity& e = entities[i]; SpawnEntity(...); e.Update(); looks safe and breaks the moment SpawnEntity grows the vector. If a function takes a reference into a vector and also appends to that same vector, that contract needs to be stated at the call site or the reference needs to become an index or an ID.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20Your item database stores 200,000 string IDs in an unordered_map and lookups spike during inventory loads. How do hash collisions and load factor affect that, and when would you write a custom hash?
The 90-second answer
Load factor is entries divided by bucket count, and it sets the average chain length. Collisions set the worst case. With 200,000 item IDs at the default load factor of 1.0, you have about 200,000 buckets and an average of one entry per bucket. That average is fine. The problem is distribution. If the hash sends many IDs to the same bucket, lookups walk that chain and compare strings one by one, and insertion into a long chain gets expensive.
Item IDs are a classic trap because they often look like item_000001, item_000002, and so on. They share a long prefix and differ only at the end. A hash that ignores the suffix, or a home-grown hash where character contributions cancel out, can put thousands of those IDs in one bucket. One inventory load then does repeated long scans.
| Setup, 200,000 IDs | Buckets | Average chain | Worst chain (hypothetical) |
|---|---|---|---|
| Good hash, load factor 1.0 | ~200,000 | 1.0 | ~8 |
| Good hash, load factor 0.5 | ~400,000 | 0.5 | ~4 |
| Hash uses only the first 4 chars | ~200,000 | 1.0 | 200,000 |
In the last row a single find can scan 200,000 strings. That is pointer chasing through node allocations, repeated for every inventory slot, and it shows up as a hitch.
Controlling load factor
Reserve before the bulk insert so rehashing happens at load time, not mid-frame, and cap the load factor if memory allows:
// C++20
std::unordered_map<std::string, ItemDef> items;
items.reserve(200000);
items.max_load_factor(0.7); // about 286,000 buckets
for (auto& def : defs) items.emplace(def.id, def);Lower load factor shortens chains at the cost of bucket memory. It does not fix a bad hash. A hash that clusters your IDs will cluster them at any load factor.
When a custom hash matters
The default std::hash<std::string> in libstdc++ is based on MurmurHash64A, not SipHash, and it is a reasonable default for ordinary keys. I write a custom hash for three reasons.
First, structured IDs. I want a hash that avalanches the differing suffix across all output bits. FNV-1a does that cheaply for non-adversarial data:
struct ItemIdHash {
using is_transparent = void; // enables heterogeneous lookup in C++20
std::size_t operator()(std::string_view sv) const noexcept {
std::uint64_t h = 1469598103934665603ULL;
for (unsigned char c : sv) {
h ^= c;
h *= 1099511628211ULL;
}
return static_cast<std::size_t>(h);
}
};
std::unordered_map<std::string, ItemDef, ItemIdHash, std::equal_to<>> items;
items.find(std::string_view{"item_000042"}); // no temporary std::stringThe transparent hash matters in hot paths. Without it, a lookup from a string_view builds a temporary std::string just to hash it. Heterogeneous lookup for unordered containers requires C++20, so this snippet is labelled accordingly.
Second, adversarial keys. A deterministic hash lets someone craft colliding IDs offline, for example through mod-supplied item packs. A per-process random seed mixed into the initial state defeats that. If I roll my own hash for that case, the seed comes from startup randomness.
Third, known format. If IDs are numeric strings or fixed hex, parsing the number and hashing the integer can be faster and better distributed than hashing characters.
How I would check it
After inserting the real ID set, I would compare size() / bucket_count() against the longest bucket found by scanning bucket(i). If the longest bucket is more than about ten times the average, the hash is failing for this data. I would also note the alternative: for a database built once at load and only read during play, a sorted vector or a flat open-addressing map often beats unordered_map on cache behavior and avoids a node allocation per entry. I keep unordered_map for registries that change at runtime.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21Walk me through implementing binary search and its lower_bound variant for a sorted leaderboard, and how you would use it to pick a loot tier from cumulative weights?
The 90-second answer
Binary search only works if the table is sorted and stays sorted. I would keep the leaderboard ascending by score, use std::lower_bound for the first entry at or above a value, and use the same primitive for loot: store cumulative weights in ascending order, draw a random integer in [0, totalWeight), and take the first cumulative weight greater than the draw. That gives O(log n) lookup, O(1) extra space, and one tested implementation for both jobs.
The invariant is the whole answer. At each step the answer, if it exists, is in [lo, hi). I halve that interval and discard the half that cannot contain it. For n = 1,000,000 entries that is at most 20 comparisons, against 500,000 on average for a linear scan. In a frame loop that difference is the difference between a lookup you can call per kill and one you cannot.
Code, C++17
#include <algorithm>
#include <vector>
struct Entry { int score; int playerId; };
// Entries sorted ascending by score. Returns insertion point:
// first index with score >= target, or entries.size() if none.
std::size_t lowerBoundScore(const std::vector<Entry>& entries, int target) {
auto it = std::lower_bound(
entries.begin(), entries.end(), target,
[](const Entry& e, int value) { return e.score < value; });
return static_cast<std::size_t>(it - entries.begin());
}std::lower_bound is a lower bound, not an equality search. It returns the leftmost position where target could be inserted without breaking order. That is exactly what a leaderboard needs for rank and insertion, and what loot needs for a weighted pick.
// Loot tiers sorted ascending by cumulative weight.
// weights: {50, 30, 15, 5} -> cumulative: {50, 80, 95, 100}
int pickLootTier(const std::vector<int>& cumulative, int roll) {
// First cumulative > roll. upper_bound, not lower_bound, here.
auto it = std::upper_bound(cumulative.begin(), cumulative.end(), roll);
return static_cast<int>(it - cumulative.begin());
}Note the split. Leaderboard rank wants the first score >= target, so lower_bound. Loot wants the first cumulative weight > roll, because a roll of exactly 50 should fall in the next tier, so upper_bound. Mixing those two up shifts every boundary by one tier and is hard to spot in playtesting because rare drops still appear, just at the wrong rate.
Worked trace
Leaderboard, ascending: [60, 80, 95, 95, 100]. Find the insertion point for 95.
| Step | lo | hi | mid | entries[mid].score | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 95 | 95 < 95 is false, search left half |
| 2 | 0 | 2 | 1 | 80 | 80 < 95 is true, search right half |
| 3 | 2 | 2 | - | - | lo == hi, answer is index 2 |
Result: index 2, the first of the two 95s. A player scoring 95 gets rank 3 (1-based), ahead of the other 95, which is the standard competition ranking choice. If you wanted the last 95 instead, you would use upper_bound and subtract one. State that choice explicitly, because tie handling is where leaderboard disputes come from.
Loot trace with cumulative [50, 80, 95, 100] and roll = 80: upper_bound returns index 2, tier 2 (the 15% tier). Roll 79 returns index 1. Roll 99 returns index 3. Roll 0 returns index 0. Each tier gets exactly its weight in rolls, which you can verify by counting: tier 0 covers rolls 0 to 49, that is 50 values.
Failure modes I check for
Unsorted input is the big one. Binary search on an unsorted array does not fail loudly. It returns a plausible index and the bug ships. I sort once at load, and after any live update I either re-sort or insert at the lower_bound position with vector::insert, which is O(n) for the shift but keeps the invariant. For a leaderboard updated every frame, that shift cost is why real games often keep a sorted array for display and a hash map from playerId to score for updates, then re-sort on a timer or on demand.
Descending order is the second trap. Most leaderboards display high to low, but std::lower_bound assumes ascending with the default comparator. Passing a descending array with the default comparator is undefined behaviour, not just wrong results. Either store ascending and iterate backwards for display, or pass a comparator that matches the order and keep it consistent everywhere.
Overflow in the midpoint is the third. (lo + hi) / 2 overflows when lo + hi exceeds the maximum of the index type. With std::size_t on a 64-bit build that needs an enormous table, but with 32-bit indices or byte offsets it is reachable. lo + (hi - lo) / 2 cannot overflow when lo <= hi, so I write it that way by default.
Empty and out-of-range cases need a defined answer before the interviewer asks. lowerBoundScore on an empty vector returns 0, which is size(), and that is correct: the insertion point is the start. pickLootTier with roll >= totalWeight returns size(), which is out of bounds for a tier index, so the caller must clamp or reject the roll. I would assert 0 <= roll && roll < totalWeight in debug builds and treat a violation as a data bug, not a player-facing error.
When not to use it
If the table is small, say under 32 entries, a linear scan is often faster in practice because it is branch-predictable and cache friendly, and it is easier to read. If lookups are by playerId rather than by score, a hash map is the right structure and binary search is the wrong tool. Binary search earns its place when the table is large, lookups are frequent, and the sort order is stable enough to maintain.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-22You have two sorted inventory lists by item ID. How do you merge them in linear time with two pointers, and how does the same idea check whether a sequence reads the same forwards and backwards?
The 90-second answer
Put one index at the start of each sorted list and only move it forward. At each step compare the two heads, emit the smaller one, and advance that pointer. When one list runs out, copy the rest of the other. That is the whole merge, and it runs in linear time because each element is visited once.
The palindrome check is the same shape with the pointers facing each other. Put one pointer at each end, compare, then move them inward. If any pair differs, the sequence is not symmetric. If they cross, it is.
Merge trace
// C++17. Item is sorted by id in both inputs.
std::vector<Item> MergeInventories(const std::vector<Item>& a,
const std::vector<Item>& b) {
std::vector<Item> out;
out.reserve(a.size() + b.size());
std::size_t i = 0, j = 0;
while (i < a.size() && j < b.size()) {
if (a[i].id <= b[j].id) out.push_back(a[i++]);
else out.push_back(b[j++]);
}
out.insert(out.end(), a.begin() + i, a.end());
out.insert(out.end(), b.begin() + j, b.end());
return out;
}Trace with a = [1, 3, 5] and b = [2, 4]:
| Step | i at | j at | Emit | Why |
|---|---|---|---|---|
| 1 | 1 | 2 | 1 | 1 < 2, advance i |
| 2 | 3 | 2 | 2 | 2 < 3, advance j |
| 3 | 3 | 4 | 3 | 3 < 4, advance i |
| 4 | 5 | 4 | 4 | 4 < 5, advance j |
| 5 | 5 | end | 5 | b exhausted, copy tail of a |
Result: [1, 2, 3, 4, 5]. Two lists of 1,000 items need at most 1,999 comparisons, not the roughly 1,000,000 comparisons a naive insert-each-item-into-sorted-list approach would cost.
Palindrome trace
bool IsSymmetric(const std::vector<int>& seq) {
if (seq.empty()) return true;
std::size_t l = 0, r = seq.size() - 1;
while (l < r) {
if (seq[l] != seq[r]) return false;
++l; --r;
}
return true;
}For [7, 3, 9, 3, 7]: compare 7 with 7, move in; compare 3 with 3, move in; l == r at 9, stop, return true. For [7, 3, 9, 4, 7], the second pair fails and it returns false after two comparisons. That pattern shows up in game code for checking a recorded input combo or a loot sequence that must read the same in reverse.
Where it breaks
The merge silently produces garbage if either input is not actually sorted, so the precondition is on the caller. Sorting first costs O(n log n) and usually erases the win unless the lists arrive sorted from storage, which inventory lists keyed by item ID often do. Using <= instead of < keeps items from a ahead of equal IDs from b, which matters when duplicate IDs carry different counts and you want a stable order. In the palindrome version, r = seq.size() - 1 underflows on an empty sequence when size_t is unsigned, which is why the empty case returns first. Both loops also assume you are not modifying the sequences while iterating, since that can invalidate the indices mid-scan.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-23Walk me through designing a stack-based undo system for a level editor that must handle coalesced drags, redo, and a 100 MB memory cap without corrupting the level on a crash mid-undo?
The 90-second answer
Use two stacks of commands, not snapshots of the level. Each edit is an object that knows how to do itself and how to reverse itself. undoStack holds what has happened, redoStack holds what was undone. A new edit clears the redo stack, because the future it described no longer exists. That one rule prevents most redo corruption.
// C++17, checked against std::vector and std::unique_ptr semantics
struct Command {
virtual ~Command() = default;
virtual void Execute() = 0;
virtual void Undo() = 0;
virtual size_t Bytes() const = 0;
};
class UndoStack {
std::vector<std::unique_ptr<Command>> undo_, redo_;
size_t capBytes_ = 100 * 1024 * 1024;
size_t usedBytes_ = 0;
public:
void Push(std::unique_ptr<Command> cmd) {
cmd->Execute();
usedBytes_ += cmd->Bytes();
undo_.push_back(std::move(cmd));
redo_.clear(); // new branch kills the old future
EvictOldest();
}
void Undo() {
if (undo_.empty()) return;
auto cmd = std::move(undo_.back()); undo_.pop_back();
cmd->Undo();
redo_.push_back(std::move(cmd));
}
void Redo() {
if (redo_.empty()) return;
auto cmd = std::move(redo_.back()); redo_.pop_back();
cmd->Execute();
undo_.push_back(std::move(cmd));
}
private:
void EvictOldest() {
while (usedBytes_ > capBytes_ && undo_.size() > 1) {
usedBytes_ -= undo_.front()->Bytes();
undo_.erase(undo_.begin()); // oldest history becomes unreachable
}
}
};Why commands beat snapshots here. A snapshot of a level with 20,000 entities at roughly 200 bytes each is 4 MB per edit. Fifty edits exhaust a 100 MB cap and undo stops working in the first minute. A transform command stores an entity id, the old transform and the new transform, about 64 bytes. A delete command stores the removed entity data once. Memory then grows with edit count, not level size, and eviction is just dropping the oldest commands.
Coalescing is where drags live or die. A brush drag fires 60 move events per second. Pushing 60 commands makes one Ctrl+Z move the brush by one frame, which users read as broken. Coalesce while the drag is active: keep a MoveCommand on top of the stack and update its newTransform on each event, executing only the delta. On mouse release, close the command so the next drag starts a fresh one. Trace:
MouseDown on Brush 7 at (10,0,0)
Push MoveCommand{7, old=(10,0,0), new=(10,0,0)}
Move to (11,0,0): update new=(11,0,0), Execute delta
Move to (12,0,0): update new=(12,0,0), Execute delta
... 47 more events, stack depth still +1
MouseUp: close command
Ctrl+Z: Undo restores (10,0,0) in one stepThe failure mode is coalescing across a release, or merging a move with a rotate that happened in between. The fix is a hard boundary: coalesce only events with the same entity, same command type and no intervening command. If in doubt, start a new command. An extra undo step is annoying. A merged command that restores the wrong transform corrupts the level silently.
Redo, delete and ids. Undoing a delete must restore the entity with its original id, because triggers, nav links and script references point at that id. So DeleteCommand captures the full entity record before removal and Undo reinserts it under the same id. If a later command referenced a newly created entity that depends on the deleted one, undo order matters: the stack is strictly LIFO, so dependents are always undone first. That invariant is the whole reason for a stack instead of a set of undoable actions. Break LIFO, for example by letting a script undo an arbitrary command, and you can resurrect an entity whose dependents are already gone.
Crash mid-undo. The in-memory stack does not survive a crash, and the level file on disk is either the pre-undo or post-undo state depending on when autosave ran. For an editor, write a small journal before applying an undo or redo batch: append the command type, entity id and inverse data to a temp file, flush it, then apply in memory. On restart, replay or discard the journal entry depending on whether the apply completed. In practice most shipped editors accept a simpler contract: autosave only on a clean command boundary, never during Undo() or Redo(), and mark the document dirty so a crash prompts recovery from the last autosave. What you must not do is autosave halfway through a multi-entity undo, such as restoring a prefab with 300 children, and leave a half restored prefab on disk.
The memory cap trade-off. Evicting the oldest commands makes the bottom of history unreachable, which is correct, but it must never evict the command currently being coalesced or one mid-undo. Evict only from the front of undo_ while the stack is idle, and if a single command exceeds the cap, for example pasting a 150 MB prefab, reject it with a dialog instead of pushing it and evicting everything else. A cap that silently drops the newest edit is worse than no cap.
| Situation | Stack state | Result |
|---|---|---|
| New edit after undo | redo cleared | old future discarded, no stale redo |
| Drag with 60 events | one coalesced command | one undo step |
| Cap exceeded | oldest commands dropped | recent history intact, bottom unreachable |
| Undo of delete | entity reinserted with same id | references stay valid |
| Crash during undo | journal decides replay or discard | file matches a command boundary |
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-24For a game object list you update and splice every frame, when does a linked list beat an array on splicing, iteration and cache locality, and when does it lose?
The 90-second answer
For a list I touch every frame, I start with a contiguous array, usually std::vector<GameObject> or a fixed pool, and only move to a linked list when splicing dominates and I already hold the node to splice. The linked list wins on one operation: removing or inserting at a known position in O(1) with no element moves and no iterator invalidation. It loses on the two operations games do far more often, full iteration and random access, because each node is a separate allocation, pointer chasing defeats the prefetcher, and a 64-byte object that would sit neatly in one cache line in an array becomes a cache miss per node in a list.
Assume a 64-byte GameObject (position, velocity, type, flags, padding to one cache line), 5,000 live objects, 60 fps, 16.6 ms budget. That is the case where the numbers decide it.
| Operation | Array / vector | Linked list (intrusive) | Why it matters in a frame |
|---|---|---|---|
| Iterate all, update physics | Sequential scan, hardware prefetcher streams it | Pointer chase per node, scattered in heap | Update runs every frame for every object |
| Remove middle element, iterator known | O(n) memmove, or O(1) swap-remove | O(1) unlink, neighbours relinked | Death, spawn, despawn during update |
| Find element to remove | O(n) scan, or O(1) via stored index | O(n) scan, or O(1) via stored iterator/pointer | You rarely have the node for free |
| Insert at head | O(n) shift, or O(1) push_back at end | O(1) | Spawn order rarely needs head insert |
| Random access, sort for render | O(1) by index, contiguous sort | No random access, sort needs copy out | Draw calls, spatial queries |
| Allocation | One allocation, amortised growth | One allocation per node unless pooled/intrusive | Fragmentation, allocator lock contention |
Iteration arithmetic
Array: 5,000 x 64 bytes = 320 KB. Streaming that at a conservative 20 GB/s from L2/L3 is about 16 microseconds, and the prefetcher hides most of it. The CPU touches each cache line once, in order.
Linked list: 5,000 nodes scattered across the heap. Even if each node is 64 bytes, the next node is not next in memory. At roughly 80 ns for an L3/DRAM miss per node, that is 5,000 x 80 ns = 0.4 ms just to walk the list, before any update logic runs. That is 25 times the array cost, and it grows as the heap fragments over a long session. std::list makes it worse: each node carries two pointers plus allocator overhead, so the object and its links rarely share a cache line cleanly.
Splicing, where the list actually wins
Removing the middle element from a vector with erase is a memmove of on average 2,500 objects, 160 KB, roughly 8 microseconds at the same bandwidth. That sounds small until you remove 200 objects in one frame, for example a particle burst expiring, which is 1.6 ms of memmoves plus iterator invalidation for anything pointing into the vector.
Swap-remove fixes the cost but not the order:
// C++17, checked against libstdc++ 13
struct GameObject { float pos[3]; float vel[3]; int type; bool active; /* pad to 64 */ };
std::vector<GameObject> objects;
void killAt(size_t i) {
objects[i] = std::move(objects.back()); // O(1), order lost
objects.pop_back();
}If order does not matter, as with particles and projectiles, swap-remove beats both erase and a linked list, and it keeps iteration contiguous. If order matters, such as a render list sorted by depth, swap-remove is out.
An intrusive list keeps O(1) unlink without per-node allocation:
struct Node { Node* next; Node* prev; GameObject obj; };
Node* head = nullptr;
void unlink(Node* n) {
if (n->prev) n->prev->next = n->next; else head = n->next;
if (n->next) n->next->prev = n->prev;
}That only helps if the caller already has the Node*, for example from a collision callback or a handle stored in a component. If you must scan to find the node, you pay the O(n) pointer chase first, and the O(1) unlink saves nothing.
Failure modes I watch for
Fragmentation and allocator cost with std::list: spawning 1,000 enemies allocates 1,000 nodes, often through a contended heap lock, and freeing them in arbitrary order leaves holes that later allocations reuse unpredictably. That shows up as a spawn hitch, not as a slow iteration, which misleads profiling.
Stale iterators and dangling handles: a raw Node* or vector index stored in a component goes stale after a swap-remove or a reallocation on growth. I store a generational handle or an index into a pool and validate it, rather than storing a pointer into a container that can move.
False economy: choosing a list to make removal O(1) while making the per-frame update 0.4 ms slower. Removal happens for the objects that die that frame. Iteration happens for all of them, every frame.
My default for a game object list is a pooled array with swap-remove, plus a free list for dead slots. I reach for an intrusive list only when I need stable handles, ordered splicing at a known node, and iteration is rare or over a small subset, such as a scene graph child list. If iteration is the hot path, contiguous storage wins even when splicing looks cheaper on paper.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-25Walk me through how you would traverse a scene graph each frame, pruning disabled subtrees and anything outside the camera frustum, without breaking inherited transforms?
The 90-second answer
Traverse depth-first, pre-order, and compute each node's world transform from its parent before you test it for culling. That ordering is the whole trick. A child inherits translation, rotation and scale from every ancestor, so its world position does not exist until the parent has been visited. If you test a child's bounding volume in local space, or prune a parent before composing its transform, you cull against the wrong place in the world.
At each node I apply two cheap tests in a fixed order: disabled first, then frustum. Disabled is a single bool check and it also skips update work, so it goes first. Frustum testing needs the world transform, so it goes second. If either test fails, I return without visiting children. That is the pruning. A disabled or off-screen parent takes its whole subtree with it, which is correct only if the flags and bounds are defined as subtree properties, and I will come back to that.
// C++17, checked against a minimal engine scene graph
struct Node {
bool enabled = true;
bool alwaysVisible = false; // UI, skybox, debug overlays
Transform local; // relative to parent
Sphere localBounds; // in local space, radius covers geometry
std::vector<std::unique_ptr<Node>> children;
Mesh* mesh = nullptr;
};
void draw(Node& n, const Transform& parentWorld,
const Frustum& frustum, DrawList& out) {
if (!n.enabled) return; // prune subtree
Transform world = parentWorld * n.local; // T * R * S inside local
if (!n.alwaysVisible && n.mesh) {
Sphere worldBounds = world.transformPoint(n.localBounds.center);
// Non-uniform scale stretches a sphere into an ellipsoid.
// Use the largest scale axis so the test stays conservative.
worldBounds.radius = n.localBounds.radius * world.maxScale();
if (!frustum.intersects(worldBounds)) return; // prune subtree
out.push_back({n.mesh, world});
}
for (auto& child : n.children)
draw(*child, world, frustum, out);
}Recursion depth here is the depth of the scene graph, typically tens of levels for a level hierarchy, so a recursive walk is fine. If you have generated chains thousands deep, for example a skeletal hierarchy built procedurally, switch to an explicit stack and push children in reverse order to keep the same pre-order sequence. The stack version also makes it easier to count visited versus drawn nodes for debugging.
Worked trace
Suppose the root has a Level node (enabled, no mesh) with children Props, Enemies and UI. Props has Chair and Table. The camera looks down a corridor, so Enemies is behind the camera and UI is alwaysVisible.
| Visit | Node | Test | Result |
|---|---|---|---|
| 1 | Level | enabled, no mesh | descend |
| 2 | Props | enabled, no mesh | descend |
| 3 | Chair | sphere inside frustum | draw, 1 mesh |
| 4 | Table | sphere outside frustum | prune, no children visited |
| 5 | Enemies | sphere outside frustum | prune whole subtree, say 40 nodes skipped |
| 6 | UI | alwaysVisible | draw regardless of frustum |
Draw list ends with 2 entries instead of 43. The saving is not just draw calls. Update, animation and physics callbacks attached to pruned nodes are skipped too, which is where most of the frame time goes in a large scene.
Where this breaks
First, bounds must cover the geometry after animation. A skinned character whose local bounds are computed from the bind pose will pop out of culling when a limb swings wide. I either inflate the sphere to cover the animation range or update bounds per frame for skinned meshes and accept the cost. A cheap check: draw the world bounds as a wireframe sphere in a debug view. If you ever see a mesh disappear while its sphere is still on screen, the bounds are wrong.
Second, a single sphere per node is conservative for elongated objects. A long wall rotated diagonally gets a sphere large enough to cover its corners, so it survives culling long after it leaves the screen. That costs overdraw, not correctness. Splitting the wall into segments, or using an oriented box for static geometry, tightens the test. I only pay for that when profiling shows the draw list is dominated by large off-screen objects.
Third, disabled semantics need a decision. If a designer disables a parent but expects an attached particle effect to keep running, subtree pruning breaks that expectation. The clean fix is to make the effect a sibling, or add an explicit ignoreParentDisabled flag and check it before returning. Silent exceptions to pruning are how you end up with effects running in a disabled level.
Fourth, frustum culling per node is not the same as culling per mesh. A node with no mesh of its own but with a huge aggregate bound will keep its children alive even when every child is off screen. I keep bounds on leaf render nodes only, and let internal nodes pass through. If a subtree is a common unit, such as a vehicle with 12 parts, an aggregate bound on the parent lets you skip all 12 with one test, and that is worth it.
Finally, shadow rendering and reflection probes run the same traversal with a different frustum. Reuse the function, pass the shadow camera frustum, and expect a second draw list. If you cache the main camera result and reuse it for shadows, objects outside the main view but inside the shadow map vanish from the shadow, which shows up as light leaking through walls.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-26On a tile map, when does BFS guarantee a shortest path and DFS not, and which would you use for enemy pathfinding?
The 90-second answer
BFS guarantees a shortest path on a tile map when every step costs the same. It expands outward in rings of increasing distance from the start, so the first time it reaches the goal, no shorter route in steps can exist. DFS makes no such guarantee. It dives down one corridor as far as it can go, and the first path it finds to the goal can wander across the whole map before it backtracks.
For enemy pathfinding on a uniform-cost grid, I would use BFS, or A* if I also have a useful heuristic. I would only reach for DFS when I need any path quickly, for example flood-filling a reachable region, or when memory is so tight that its stack matters more than path length.
Why BFS is optimal here, and DFS is not
Treat each tile as a vertex and each walkable neighbour as an edge. With 4-directional movement, every edge has weight 1. BFS keeps a queue of tiles to visit next, ordered by the distance at which they were first discovered. All tiles at distance 1 are processed before any tile at distance 2, and so on. When the goal is dequeued, its recorded distance is minimal, because any alternative route would have to pass through a tile at the same or greater distance.
DFS keeps a stack instead. It commits to one neighbour, then that neighbour's neighbour, until it hits a wall or a dead end. It may cross the map to reach the goal by a long route while a two-step route sits unexplored in another branch.
A small trace makes the difference concrete. Tiles are walkable except #. S is the start, G is the goal.
S . .
# # .
G . .BFS order: S, then (0,1), then (0,2), then (1,2), then (2,2), then (2,1), then G at distance 6. That is the only route, and BFS reports 6.
Now open a shortcut and DFS can miss it:
S . G
. # .
. . .If DFS tries the downward neighbour first, it walks S to (1,0) to (2,0) to (2,1) to (2,2) to (1,2) to (0,2) to G, a path of 7 steps, before it ever tries the direct rightward step from S. BFS still finds S to (0,1) to G in 2 steps, because (0,1) is dequeued before any tile at distance 2 or more.
Code shape
// C++17, grid indexed by (x, y), 4-directional, uniform cost
std::vector<Point> bfs(const Grid& g, Point start, Point goal) {
std::queue<Point> q;
std::unordered_map<Point, Point> cameFrom;
q.push(start);
cameFrom[start] = start;
while (!q.empty()) {
Point cur = q.front(); q.pop();
if (cur == goal) break;
for (Point n : g.neighbours(cur)) {
if (!cameFrom.count(n)) {
cameFrom[n] = cur;
q.push(n);
}
}
}
// Reconstruct by walking cameFrom back from goal to start.
// If goal is absent from cameFrom, there is no path.
}The cameFrom check is what stops the search revisiting tiles. Without it, BFS would reprocess the same tile through every possible route to it.
Costs and limits
| BFS | DFS | |
|---|---|---|
| Shortest path, uniform cost | Yes, fewest steps | No |
| Time | O(V + E) | O(V + E) |
| Extra memory | Queue can hold O(V) tiles in the worst case | Stack holds O(depth), often far less, but worst case also O(V) |
| Typical game use | Shortest path on a grid, flood fill by distance | Reachability, maze generation, any-path search |
On a 256 by 256 tile map, V is 65,536. BFS may enqueue a large fraction of that before it finds a distant goal, so in practice I would switch to A* with a Manhattan heuristic for 4-directional movement. A* keeps the same optimality guarantee when the heuristic never overestimates the remaining steps, and it usually expands far fewer tiles.
The guarantee also breaks the moment tiles stop costing the same. If mud costs 5 and road costs 1, BFS counts steps and can return a 3-step route through mud over a 6-step route along road, even though the road route is cheaper. That case needs Dijkstra, or A* with the true step costs in the priority queue. BFS is the right tool only while cost per step is constant, which is the assumption to state out loud in the interview.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-27Walk me through how an inadmissible A* heuristic can return a suboptimal path on a diagonal grid, and how you would test for that before shipping it?
The 90-second answer
A* ranks nodes by f(n) = g(n) + h(n), where g is the cost already paid from the start and h estimates the cost still to pay to the goal. If h never overestimates that remaining cost, it is admissible and the first time the goal leaves the open list, its g is optimal. Break that condition and A* can still return a path, it just has no guarantee that path is cheapest. The classic way to break it on a grid is to keep a 4-directional heuristic after enabling diagonal movement.
A concrete trace
Take a small graph first, because the grid case is the same idea with more nodes. Two routes from S to G:
S -> A -> Gcosts2 + 3 = 5(optimal)S -> B -> Gcosts3 + 3 = 6
True remaining costs are h(A)=3 and h(B)=3. Now use a bad heuristic that overestimates A and underestimates B: h(A)=5, h(B)=1.
| Step | Expanded | g | h (bad) | f = g+h | Consequence |
|---|---|---|---|---|---|
| 1 | S | 0 | 4 | 4 | Opens A (f=7) and B (f=4) |
| 2 | B | 3 | 1 | 4 | Opens G via B with g=6, f=6 |
| 3 | G | 6 | 0 | 6 | Popped before A (f=7), search stops |
Result: path cost 6, not 5. Nothing crashed. The search terminated normally and returned a valid, suboptimal path. That is why bad heuristics are hard to spot in playtests. Units arrive, just by a longer route.
On a grid with diagonal moves costing sqrt(2) and orthogonal moves costing 1, Manhattan distance |dx| + |dy| overestimates. A target one diagonal step away has Manhattan distance 2 but true cost 1.414. The admissible replacement is the octile distance:
// C++, checked against a grid with orthogonal cost 1, diagonal cost sqrt(2)
float OctileHeuristic(Point a, Point b) {
int dx = std::abs(a.x - b.x);
int dy = std::abs(a.y - b.y);
int lo = std::min(dx, dy);
int hi = std::max(dx, dy);
return hi + (std::sqrt(2.0f) - 1.0f) * lo;
}
float ManhattanHeuristic(Point a, Point b) {
return std::abs(a.x - b.x) + std::abs(a.y - b.y); // inadmissible here
}For dx=3, dy=3, octile gives 3 + 0.414*3 = 4.24, which equals three diagonal steps. Manhattan gives 6, an overestimate of 41%.
How I test for it before shipping
Admissibility is a claim about every node, so I check it against ground truth instead of eyeballing paths. Run Dijkstra backwards from the goal over the same navmesh or grid. That gives the exact remaining cost dist(n, G) for every reachable node. Then assert, for every node:
h(n) <= dist(n, G) + epsilonI also check consistency, h(n) <= cost(n, m) + h(m) for every edge n -> m. Consistency is stronger. With a consistent heuristic, a node never needs to be reopened once closed. With an admissible but inconsistent heuristic, A* is still optimal only if the implementation reopens closed nodes when a cheaper g shows up. Plenty of shipped implementations use a closed set with no reopening, which silently turns inconsistency into suboptimal paths.
In practice I run both checks over generated maps: random obstacle densities, narrow corridors, open fields. A heuristic that passes on an empty map can fail beside a wall, because the wall raises the true cost while h stays low. That failure direction is safe for optimality but slow, since A* expands extra nodes. The dangerous direction is overestimation, which the Dijkstra comparison catches directly.
The deliberate trade-off
Games often use weighted A*, f(n) = g(n) + w * h(n) with w between 1.5 and 3, for crowds of NPCs. On a 10,000-node map in our tests, w=2 cut node expansions by roughly 40% and raised average path cost by about 6%. That is a reasonable trade for ambient creatures and a bad one for a boss that must take the intended route, or for any system where path cost feeds a budget, such as a tower defence enemy that must be guaranteed the shortest route. My rule: admissible and consistent for gameplay-critical paths, weighted only where a few percent of extra distance is invisible and the frame budget is real.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-28When would you pick Dijkstra over A* for enemy pathfinding, and what breaks if your heuristic overestimates the true cost or you have no useful heuristic at all?
The 90-second answer
Dijkstra is A* with the heuristic set to zero. Both pop the lowest-cost node from a priority queue, relax its neighbours, and stop when the goal is popped. The difference is what that cost means. Dijkstra ranks nodes by cost from the start, g. A* ranks them by g + h, where h estimates the remaining cost to the goal. If h is admissible, meaning it never overestimates the true remaining cost, A* returns the same optimal path as Dijkstra while usually expanding far fewer nodes. If h is missing, zero, or misleading, that advantage disappears and can turn into a wrong path.
| Dijkstra | A* with admissible h | A* with overestimating h | |
|---|---|---|---|
| Priority | g | g + h | g + h, inflated |
| Expansions on a 10,000-node navmesh | Most reachable nodes in the worst case | Nodes near the start-to-goal corridor | Often fewest, but path may be suboptimal |
| Optimality | Guaranteed with non-negative edge costs | Guaranteed if h is admissible and consistent, or nodes are reopened | Not guaranteed |
| Main risk | Too slow for many agents or frequent replans | Bad h design | Greedy traps, missed shortcuts |
Worked trace
Take a 20 by 20 grid, four-directional movement, cost 1 per step, start at the bottom left and goal at the top right. The true distance is 38 steps. Dijkstra has no reason to prefer a node at (10, 10) over one at (0, 19), so it expands roughly in a diamond around the start. In an empty grid that is most of the 400 cells before the goal is popped.
With Manhattan distance as h, every node on a shortest route scores g + h = 38. Nodes off that corridor score higher. A* still expands nodes in order of increasing f, but in practice it walks the corridor and expands a few dozen nodes. That gap is the whole reason A* exists in games. On a navmesh with 50,000 polygons and 200 enemies replanning every half second, Dijkstra per enemy is rarely affordable. A* with a decent h often is.
// C++17. Edge costs are non-negative. h(id) must be in the same units as g.
struct Item {
float f;
int id;
bool operator<(Item const& other) const {
return f > other.f; // reversed: priority_queue is a max-heap
}
};
std::priority_queue<Item> open;
open.push({h(start), start});
g[start] = 0.0f;
while (!open.empty()) {
int u = open.top().id; open.pop();
if (u == goal) break; // first pop of goal is optimal only under the conditions below
for (auto [v, w] : neighbours(u)) {
float tentative = g[u] + w;
if (tentative < g[v]) {
g[v] = tentative;
open.push({tentative + h(v), v});
}
}
}When the heuristic misleads
Admissible means h(n) <= true_cost(n, goal) for every node. Consistency is stronger: h(n) <= w(n, v) + h(v) for each edge. Consistency guarantees that the first time a node is popped its g is final, so a closed list is safe. With only admissibility, you may need to reopen a closed node if a cheaper g arrives later. Skip the reopen and you can lock in a suboptimal path.
Overestimation breaks optimality directly. Suppose a level has a portal that moves the player from the west side to a cell 5 steps from the goal. Euclidean distance ignores the portal, so that is fine. The dangerous case is the reverse: a jump pad, a flying enemy, or a one-way drop that makes the true cost far lower than straight-line distance suggests. If your h assumes ground movement at walking speed, it overestimates for a flying unit. A* then treats the direct route as expensive, detours, and may return a path that is 3 times longer than the real one. Worse, if you prune nodes whose f exceeds a budget, the overestimate can prune the actual solution.
A common game fix is weighted A*, using g + 2*h or g + 3*h. That trades optimality for speed and is fine for background enemies where a slightly silly route is acceptable. It is not fine for a boss, a racing line, or any path the player can compare against a known optimum. Say which behaviour you chose in the design doc, because playtesters notice the difference.
When there is no useful heuristic
Some maps defeat spatial heuristics. A maze with teleporters, a level where verticality matters more than horizontal distance, or costs driven by stealth zones rather than distance. Then h = 0 is honest, and you are running Dijkstra. The optimisation that matters then is sharing the work. If 200 zombies all path to the same player position, run one reverse Dijkstra, or BFS on a uniform grid, from the goal over the navmesh and store the resulting distance field. Each zombie then just walks downhill to the neighbour with the lowest stored cost. One search replaces 200.
That flow field has its own failure mode. It is stale the moment a door closes or a dynamic obstacle appears. Recompute on a timer, on navmesh changes, or when an agent reaches a local minimum where no neighbour improves. Agents stuck at a local minimum are the detection signal, not a log line.
In short: use A* when you can name an admissible h in the same cost units as your edges, use Dijkstra or a shared distance field when you cannot, and treat any inflated heuristic as a deliberate trade of path quality for expansions saved.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-29Walk me through how you would use a heap to schedule AI think events and gameplay timers by earliest deadline, and how you would handle rescheduling or cancelling an event?
The 90-second answer
Use a min-heap keyed by deadline. The heap gives me the next event in O(1) at the top and insert or remove in O(log n), so each frame I pop every event whose deadline has passed, run it, and push its next occurrence if it repeats. I never scan all NPCs to find who is due.
The catch is rescheduling. A heap does not support changing a key in place, and std::priority_queue does not even support removing an arbitrary element. I handle that with lazy deletion: every event carries a generation number, and cancelling or rescheduling bumps the generation and pushes a fresh entry. Stale entries are discarded when they reach the top.
Core structure
// C++17. Game time is a monotonic float in seconds, advanced once per frame.
struct TimerEvent {
float deadline;
uint32_t id; // NPC or timer owner
uint32_t generation; // bumped on every reschedule or cancel
bool operator<(TimerEvent const& other) const {
return deadline > other.deadline; // reversed: priority_queue is a max-heap
}
};
std::priority_queue<TimerEvent> heap;
std::unordered_map<uint32_t, uint32_t> liveGeneration; // id -> current generation
void schedule(uint32_t id, float delay) {
uint32_t gen = ++liveGeneration[id];
heap.push({now + delay, id, gen});
}
void cancel(uint32_t id) { ++liveGeneration[id]; } // old entries become stale
void tick() {
while (!heap.empty() && heap.top().deadline <= now) {
TimerEvent e = heap.top(); heap.pop();
auto it = liveGeneration.find(e.id);
if (it == liveGeneration.end() || it->second != e.generation) continue; // stale
runThink(e.id); // AI decides, then typically calls schedule(id, nextInterval)
}
}runThink pushes the next think time itself, which keeps periodic behaviour in one place. If an NPC dies, I call cancel(id) and erase its generation entry. The pending heap entry stays until it surfaces, then the generation check drops it. That costs one dead entry per cancel, which is fine at game scale.
Worked trace
Suppose now = 10.00 and the heap holds, in deadline order: NPC 7 at 10.05 (gen 3), NPC 2 at 10.10 (gen 1), NPC 7 at 10.20 (gen 4), NPC 9 at 10.30 (gen 1). NPC 7 was rescheduled at 10.00, so gen 3 is stale.
| Frame time | Action | Result |
|---|---|---|
| 10.06 | Pop NPC 7, gen 3. Generation mismatch, discard. | No think runs. |
| 10.11 | Pop NPC 2, gen 1. Matches. Run think, schedule next at 10.36. | Heap top becomes NPC 7 at 10.20. |
| 10.21 | Pop NPC 7, gen 4. Matches. Run think. | Correct single think for NPC 7. |
Without the generation check, NPC 7 would think twice, once at 10.05 from the stale entry and again at 10.20. That double think is the classic bug with lazy deletion done halfway.
Why a heap, and when it loses
| Approach | Find next due | Insert | Cancel one timer | Problem |
|---|---|---|---|---|
| Scan all NPCs each frame | O(n) | O(1) | O(1) | 5,000 NPCs means 5,000 checks per frame even when nothing is due |
| Sorted vector | O(1) | O(n) shift | O(n) | Rescheduling a frequent thinker shifts thousands of entries |
| Min-heap | O(1) peek, O(log n) pop | O(log n) | O(1) with lazy deletion | Stale entries accumulate if cancels outnumber pops |
The arithmetic favours the heap quickly. With 5,000 NPCs thinking on average every 0.25 s, about 20,000 thinks per second are due, but a scan still touches 5,000 entries 60 times a second, 300,000 checks, to find them. The heap touches only the due entries plus log2(5000), about 12 comparisons, per insert or pop.
A timing wheel beats the heap when timers are numerous, short lived, and only need coarse granularity, for example thousands of particle or audio one-shots bucketed by frame. It gives O(1) insert and advance, but deadlines snap to bucket boundaries and long timers need multiple wheel levels. For AI thinks, where I want exact deadlines and a few thousand entries, the heap is simpler and precise enough.
Failure modes I watch for
Stale entries piling up: if a system cancels timers in a burst, say clearing all NPC timers on level unload, the heap can hold tens of thousands of dead entries. Popping them is still O(log n) each, so I rebuild the heap from scratch on bulk clears instead of cancelling one by one.
Clock choice: deadlines must use the same clock that drives gameplay, a monotonic game time that pauses with the game. Using wall clock time breaks when the player pauses or the frame rate dips, and using frame count breaks when the timestep changes.
Float drift on periodic timers: rescheduling as now + interval accumulates error if a frame runs late, so a thinker can drift. For strict periodicity I schedule from the previous deadline, e.deadline + interval, and clamp catch-up to one or two iterations so a hitch does not trigger a burst of backlogged thinks.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-30Walk me through using bit flags for input states, collision layers, and ability flags, and how you test and toggle individual bits?
The 90-second answer
Give each flag exactly one bit, store the set in an unsigned integer, and test membership with &. Setting is |, clearing is & ~bit, toggling is ^. That one pattern covers input state, collision layers and ability flags, and it costs one integer compare per test.
// C++17, checked in a gameplay module
#include <cstdint>
enum class Input : std::uint32_t {
None = 0,
Left = 1u << 0,
Right = 1u << 1,
Jump = 1u << 2,
Fire = 1u << 3
};
enum class Layer : std::uint32_t {
Player = 1u << 0,
Enemy = 1u << 1,
World = 1u << 2,
Projectile = 1u << 3
};
enum class Ability : std::uint32_t {
Dash = 1u << 0,
DoubleJump = 1u << 1,
Glide = 1u << 2
};
inline bool Has(std::uint32_t flags, std::uint32_t bit) {
return (flags & bit) != 0;
}
inline void Set(std::uint32_t& flags, std::uint32_t bit) {
flags |= bit;
}
inline void Clear(std::uint32_t& flags, std::uint32_t bit) {
flags &= ~bit;
}
inline void Toggle(std::uint32_t& flags, std::uint32_t bit) {
flags ^= bit;
}Callers cast the enum to std::uint32_t at the boundary, or make Has a template on the enum type. Keeping the storage type explicit avoids signed shift surprises.
Worked trace
Start with input = 0. Pressing Left and Jump sets two bits:
Set(input, Left) // input = 0001
Set(input, Jump) // input = 0101
Has(input, Fire) // 0101 & 1000 = 0 -> false
Has(input, Jump) // 0101 & 0100 = 0100 -> true
Clear(input, Left) // input = 0100
Toggle(input, Fire) // input = 1100Collision uses the same test, but between two masks. An object carries a layer mask and a collision mask. Two objects can collide when the masks overlap:
bool CanCollide(std::uint32_t aMask, std::uint32_t bMask) {
return (aMask & bMask) != 0;
}
// Player (0001) vs Enemy (0010): 0001 & 0010 = 0, no collision
// Projectile (1000) vs World (0100) plus Enemy (0010): 1000 & 0110 = 0
// Projectile (1000) vs Enemy (0010) plus Projectile (1000): overlap, collisionThat is why a projectile can be set to hit World and Enemy while ignoring Player, without adding a special case per pair.
| Operation | Expression | Effect |
|---|---|---|
| Test one bit | (flags & bit) != 0 | True only if that bit is set |
| Set | flags | bit | Turns the bit on, leaves others alone |
| Clear | flags & ~bit | Turns the bit off, leaves others alone |
| Toggle | flags ^ bit | Flips the bit |
| Test overlap | (a & b) != 0 | True if any bit is shared |
| Test all bits | (flags & required) == required | True only if every required bit is set |
The last row matters for abilities. A door that needs Dash and DoubleJump checks (abilities & required) == required, not two separate Has calls that could pass on a partial set.
Where this breaks
Shift width is the classic bug. 1 << 31 on a signed 32-bit int overflows, which is undefined behaviour in C++. 1u << 31 is fine, and 1ULL << 40 is needed past 32 flags. Shifting by 32 or more on a 32-bit value is also undefined, so a flag enum that grows past the storage width fails silently in some builds and loudly in others. I keep a static_assert on the count or move to std::uint64_t before the 32nd flag.
Overlapping values break the test. If two enum entries share a bit, Has cannot tell them apart and clearing one clears the other. A quick check in review: every non-zero entry must be a power of two, and Left | Right must not equal another entry.
Bit flags also stop being the right tool past about 64 flags, when you need to count how many are set, iterate them by name for a save file or UI list, or store per-flag metadata. At that point std::bitset<128> or a plain array of bools reads better and serialises without a hand-written bit packing step. For a handful of hot, per-frame states, the integer wins on cache footprint and branch cost.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-31Design a finite state machine for an enemy with idle, patrol, chase and flee states where a fleeing enemy's safe post becomes unreachable, health regenerates across the flee threshold, and the player reappears mid-flee: what transitions are valid and how do you avoid oscillation and dead states?
The 90-second answer
I would treat the four states as intents and make every transition pass three checks: the guard is true, the destination is reachable, and the enemy has stayed long enough in the current state for the change to be meaningful. That third check plus separate enter and exit thresholds stops oscillation when health regenerates across the flee line or the player blinks in and out of view during a flee.
The hard case is Flee. Flee has a destination, not just a direction. If that safe post is unreachable, staying in Flee forever is a dead state. If the player reappears while fleeing, jumping straight back to Chase recreates the flicker the hysteresis was meant to prevent. So Flee exits only to Patrol or Idle, never directly to Chase, and only when health, threat and path checks all pass together.
| From | To | Guard |
|---|---|---|
| Idle | Patrol | idle timer expired and next waypoint reachable |
| Idle | Chase | player visible, distance under 12 m, in field of view |
| Idle | Flee | health under 30 or threat flagged |
| Patrol | Idle | reached waypoint pause point |
| Patrol | Chase | player visible, distance under 12 m |
| Patrol | Flee | health under 30 |
| Chase | Flee | health under 30 |
| Chase | Patrol | unseen for 3 s and distance over 16 m |
| Flee | Patrol | health over 45, threat unseen for 2 s, patrol waypoint reachable |
| Flee | Idle | health over 45, threat unseen for 2 s, safe post reachable |
| Flee | Flee | safe post unreachable: hold position and retry path every 0.5 s |
Priority inside one fixed update is Flee entry first, then Flee exit, then Chase entry, then routine transitions. Without that order, a frame where health is 29 and the player is at 10 m could enter Chase and Flee in the same tick depending on which system runs first.
enum class State { Idle, Patrol, Chase, Flee };
State NextState(State cur, const Perception& p, float timeInState) {
if (p.health < 30.0f) return State::Flee;
if (cur == State::Flee) {
bool recovered = p.health > 45.0f && p.timeSinceThreatSeen > 2.0f;
if (!recovered || timeInState < 2.0f) return State::Flee;
if (p.safePostReachable) return State::Idle;
if (p.patrolWaypointReachable) return State::Patrol;
return State::Flee; // hold, retry path on timer, never Chase
}
if (p.canSeePlayer && p.distance < 12.0f) return State::Chase;
if (cur == State::Chase) {
return (p.timeSinceSeen > 3.0f && p.distance > 16.0f)
? State::Patrol : State::Chase;
}
if (cur == State::Idle) return p.idleTimerExpired ? State::Patrol : State::Idle;
if (cur == State::Patrol) return p.atWaypointPause ? State::Idle : State::Patrol;
return cur;
}Enter and exit actions run once per transition. Enter Flee requests a path to the safe post and raises speed. If that request fails, the state stays Flee but movement switches to hold position. Exit Flee clears the flee path before Patrol or Idle claims movement. Keeping path requests out of the per-frame update avoids spamming the pathfinder every tick while the post is blocked.
Worked trace
Frame 0: health 100, Idle, player at 11 m and visible. Transition to Chase. Frame 200: health falls to 29. Priority check returns Flee, even though the player is still visible. Frame 260: the player reappears at 9 m after a brief occlusion. The enemy stays in Flee because Chase entry is not evaluated while in Flee. Frame 340: health regenerates to 38. Still Flee, since 38 sits below the 45 recovery line. Frame 420: health reaches 50 and the threat has been unseen for 2.1 s, but the safe post path fails. The enemy remains in Flee, holds position, and retries the path at frame 450. Frame 480: the patrol waypoint is reachable, so it exits to Patrol. It does not resume Chase until a later frame where the player is visible under 12 m, which gives a clean re-engagement instead of a mid-flee snap.
Distance uses the same split. Chase starts under 12 m and ends only after 3 s unseen and beyond 16 m. A player hovering at 13 m therefore keeps the enemy in Chase without repeated transitions.
Failure modes I test for
A state with no reachable exit is a soft lock, so I verify every state can reach Patrol or Idle under blocked-path conditions. A second transition site in movement or animation code causes double entry actions, so I keep one transition function called once per fixed update. Path failure handled only in Flee movement code leaves the state machine claiming Flee while the body stands still with no retry timer. I also log transitions with frame numbers in playtests. A healthy enemy changes state a handful of times per minute. Hundreds per minute names the exact pair thrashing, usually Chase and Flee or Flee and Patrol, and points at a threshold or timer that needs widening.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-32How would you use the observer pattern so a health change updates the HUD, audio and achievements without the health component knowing about them?
The 90-second answer
Health is the subject. It owns the value and raises HealthChanged(old, current, source) after the value actually changes. HUD, audio and achievements subscribe to that event and unsubscribe when they are destroyed. Health never stores a HUD, a clip or an achievement ID, so adding a new listener does not touch damage code.
// C# / Unity, checked against Unity 2022 LTS
public sealed class Health : MonoBehaviour
{
public event Action<int, int> HealthChanged; // old, current
public int Current { get; private set; } = 100;
public void ApplyDamage(int amount, GameObject source)
{
int old = Current;
Current = Mathf.Clamp(Current - amount, 0, 100);
if (Current != old)
HealthChanged?.Invoke(old, Current);
}
}
public sealed class Hud : MonoBehaviour
{
[SerializeField] Health health;
[SerializeField] Image bar;
void OnEnable() => health.HealthChanged += OnHealthChanged;
void OnDisable() => health.HealthChanged -= OnHealthChanged;
void OnHealthChanged(int old, int current)
{
bar.fillAmount = current / 100f;
}
}Audio does the same subscription and plays a hurt clip only when current < old. An achievement listener checks thresholds, for example first damage, below 25, and death, and fires once per run by tracking flags it owns.
Why this shape, and where it breaks
The contract is one direction of knowledge. Health publishes facts. Listeners decide what the facts mean. That keeps a damage-over-time tick, a fall and a melee hit on the same path, and it lets a test double subscribe in an edit-mode test without a scene.
Three failure modes decide whether it survives a session.
-
Dangling listener. A HUD destroyed on a scene load stays subscribed if
OnDisableis missing. The next hit calls a dead object. In Unity that throws or silently no-ops depending on the type, and in raw C++ a stored raw pointer orstd::functionto a dead object is undefined behaviour. Unsubscribe in the paired disable or destructor, not in a cleanup pass you hope runs. -
Mutation during dispatch. A listener that unsubscribes itself, or kills the player and unloads the level, changes the list while it is being walked. A plain
forover a live list can skip the next listener or call one twice. Copy the delegate list before invoking, which C# events andGetInvocationList()do for you, or iterate a snapshot in a custom list. Trace: health drops 100 to 0, HUD handler runs and disables itself, audio handler must still run for that same hit. With a snapshot it does. With live iteration it may not. -
Ordering and reentrancy. HUD before audio before achievements is not guaranteed by subscription order in every custom implementation, and an achievement that heals the player raises a second event inside the first. Decide whether nested events are allowed. If they are, guard the achievement so it fires once and do not let a listener call
ApplyDamagerecursively without a depth check.
Choosing the mechanism
| Approach | Cost per hit | Lifetime risk | Best fit |
|---|---|---|---|
| C# event / delegate | One multicast call, no per-frame allocation if handlers are cached | Low if unsubscribe is paired | HUD, audio, achievements on the same object graph |
| UnityEvent in the Inspector | Slower, allocates on invoke in older versions, serialised wiring | Wiring can point at destroyed objects after prefab changes | Designer-wired UI, not hot gameplay paths |
Custom C++ signal with std::vector<Observer*> | Cheap, no allocation after reserve | High, raw pointers dangle unless you add weak handles or tokens | Engine code where you control lifetimes |
Polling in Update | No events, but every listener reads health every frame | None | One listener, or state that must be sampled anyway |
For a C++ engine I would return a connection token from Connect and require Disconnect(token) in the observer destructor, or store std::weak_ptr to the observer. That makes the dangling case a no-op instead of a crash.
Performance is rarely the issue at damage rates. A player takes maybe 20 hits per second. Even 10 listeners is 200 calls per second, nothing against a 16.6 ms frame. The cost that matters is allocation and accidental per-frame polling, so keep the event off Update and do not allocate a lambda per hit. Cache the handler as a field if you create it in OnEnable.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-33How would you use composition and the strategy pattern to make weapons and abilities interchangeable without a deep inheritance hierarchy?
The 90-second answer
I would keep a small Weapon class that owns data and state, and delegate behaviour to a strategy object that can be swapped at runtime. Inheritance forces every variant into one tree. A shotgun that inherits from a rifle inherits burst logic it does not want, and adding a charge shot means a new subclass, a new branch in every if (type == ...) check, and a rebuild of the hierarchy when designers want a weapon that fires a spread of charged projectiles.
With composition, Weapon holds a unique_ptr<FireStrategy> plus stats such as damage and cooldown. The strategy answers one question: given this weapon and this frame, what happens on trigger pull. A new behaviour is a new strategy class, not a new weapon class. The same strategy can be reused across weapons, and a buff can swap it without touching the weapon.
// C++17
struct FireContext { float dt; bool triggerHeld; bool triggerPressed; };
struct FireStrategy {
virtual ~FireStrategy() = default;
virtual void Update(Weapon& w, const FireContext& ctx) = 0;
};
struct AutoFire : FireStrategy {
void Update(Weapon& w, const FireContext& ctx) override {
if (ctx.triggerHeld && w.CooldownReady()) {
w.SpawnProjectile(w.Muzzle(), w.AimDir());
w.ResetCooldown(0.12f);
}
}
};
struct BurstFire : FireStrategy {
int shotsLeft = 0;
void Update(Weapon& w, const FireContext& ctx) override {
if (ctx.triggerPressed) shotsLeft = 3;
if (shotsLeft > 0 && w.CooldownReady()) {
w.SpawnProjectile(w.Muzzle(), w.AimDir());
w.ResetCooldown(0.07f);
--shotsLeft;
}
}
};
class Weapon {
public:
void SetStrategy(std::unique_ptr<FireStrategy> s) { strategy_ = std::move(s); }
void Update(const FireContext& ctx) { strategy_->Update(*this, ctx); }
// SpawnProjectile, CooldownReady, ResetCooldown, Muzzle, AimDir ...
private:
std::unique_ptr<FireStrategy> strategy_;
};Abilities follow the same shape. A DashAbility and a HealAbility both hold an ActivationStrategy that decides whether the input is valid, what it costs, and what effect runs. The ability class handles cooldown, charges and UI state once.
Why the hierarchy breaks first
| Inheritance | Composition with strategy | |
|---|---|---|
| Add burst to a shotgun | New subclass, or override that fights the parent | Assign BurstFire to the existing shotgun asset |
| Combine spread with charge | Diamond or duplicated code across branches | One strategy that does both, or chain two strategies |
| Runtime buff changes behaviour | Cast, flag checks, or a parallel class | SetStrategy on the live weapon |
| Data-driven tuning | Stats scattered in subclass constructors | Stats in a data asset, strategy chosen by ID |
The trace for a buff makes the difference concrete. Frame 1: a rifle holds AutoFire, cooldown 0.12 s, and fires every 0.12 s while held. A pickup grants burst. The game calls rifle.SetStrategy(make_unique<BurstFire>()). Frame 2: one press fires three projectiles at 0.07 s intervals, then stops even though the trigger is still held. No rifle subclass was created, and the same BurstFire object type already serves the burst pistol.
Failure modes I would guard against
Lifetime is the common one. A raw FireStrategy* stored on the weapon dangles if the strategy is owned by a temporary buff or a shared config object that gets reloaded. Owning it with unique_ptr on the weapon, or sharing it with shared_ptr when several weapons genuinely share one stateless strategy, makes the owner explicit. A stateless strategy such as AutoFire can be shared. BurstFire cannot, because shotsLeft is per weapon state. Sharing it would make two weapons consume each other's burst count.
The second failure is putting state in the wrong place. If cooldown lives in the strategy, swapping strategies resets or duplicates it, and two strategies on one weapon disagree about whether it can fire. Cooldown, ammo and muzzle position belong on Weapon. The strategy only decides when to call SpawnProjectile and ResetCooldown.
The third is allocation and dispatch cost in the hot path. One virtual call per weapon per frame is noise next to physics and rendering. Creating a strategy object every frame is not. Strategies are created on equip, on buff apply, or on load, then reused. If a design needs per-frame behaviour selection with zero allocation, I would keep a small enum and a switch inside one strategy, or preallocate one instance of each strategy per weapon and swap pointers to them.
I would still use inheritance inside the strategy family, where the interface is genuinely shared and the variants are closed. The line I draw is between varying behaviour, which gets composition, and varying identity, which can keep a class hierarchy. Weapons and abilities vary in behaviour far more often than they vary in identity, so that is where the strategy pays for itself.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-34Why do per-frame allocations in Update cause GC hitches in Unity, and how do you spot them with the Profiler?
The 90-second answer
Unity's managed heap is collected by a Boehm based collector. It is conservative, non-moving and non-generational, so there is no young generation that gets collected cheaply while old objects are ignored. When allocation crosses the heap threshold, the collector pauses the main thread, scans the heap and stack to find live objects, and frees the rest. A collection that takes 8 ms inside a 16.6 ms frame is a visible hitch, even if your gameplay code took 2 ms.
In the Profiler, record gameplay and look for a GC spike on the Timeline and non-zero GC Alloc in the CPU view. A clean Update shows 0 B GC Alloc. Anything allocated every frame is borrowing against the next collection, and the pause grows with the number of live managed objects because the collector must trace them.
Why incremental GC does not remove the problem
Unity offers Incremental GC in Player Settings. It slices the collection work across frames instead of doing it in one stop-the-world pause, which lowers the worst frame time. It does not make allocation free. It adds per-frame overhead while collection is in progress, can extend total collection time, and still has to run. If you allocate 1 KB per frame at 60 fps, that is 60 KB per second and 3.6 MB per minute in this hypothetical trace. Incremental GC spreads the scan, but the heap still fills and the work still happens. The fix remains to allocate nothing in the hot path. Calling GC.Collect manually only chooses where the pause lands, usually making it larger.
What allocates, and what to do instead
Pattern in Update | Why it allocates | Replacement |
|---|---|---|
| --- | --- | --- |
| String concatenation or interpolation for HUD text | New string each call | Assign only when the value changes, reuse a StringBuilder to build it |
LINQ Where, Select, ToList | Iterator, closure and result list | Plain for loop over a cached array or List<T> |
| Captured lambda passed as a delegate | Closure object per call | Cache the delegate, pass state explicitly |
GetComponent<T>() or object search per frame | Lookup work, and search APIs return arrays | Cache the reference in Awake |
new List<T>() per frame | List plus backing array | Allocate once, call Clear() and reuse |
Struct passed to object, an interface, or a non-generic collection | Boxing copies the struct to the heap | Keep the value typed, avoid foreach over IEnumerable for structs |
For object searches, FindObjectsOfType is superseded by FindObjectsByType in Unity 2023.1 and later, with sort mode options. Neither belongs in Update. Cache the result, or maintain your own registry as objects spawn and despawn.
void Update()
{
var enemies = FindObjectsByType<Enemy>(FindObjectsSortMode.None)
.Where(e => e.IsAlive).ToList();
hud.text = "Enemies: " + enemies.Count;
foreach (var e in enemies) e.Tick();
}That allocates the search array, the LINQ iterator and list, and a string every frame. The replacement caches the list and the last displayed count:
readonly List<Enemy> enemies = new List<Enemy>();
global::System.Text.StringBuilder sb = new global::System.Text.StringBuilder();
int lastShown = -1;
void Update()
{
int alive = 0;
for (int i = 0; i < enemies.Count; i++)
{
var e = enemies[i];
if (!e.IsAlive) continue;
e.Tick();
alive++;
}
if (alive == lastShown) return;
lastShown = alive;
sb.Clear();
sb.Append("Enemies: ").Append(alive);
hud.text = sb.ToString();
}Caching versus pooling
Caching a reference is right for stable objects such as a Transform or a HUD component. It is worse when the set changes often, for example enemies spawning and dying. Then the cache needs invalidation on every spawn and despawn, and a missed invalidation leaves a stale entry. Pooling is right for short-lived gameplay objects such as projectiles and particles, where reuse also avoids instantiation and Awake cost. Pooling is worse when objects are rarely reused, because the pool retains memory for no benefit and can grow without bound if the peak is brief.
Failure modes and how you detect them
A stale cache throws MissingReferenceException after the target is destroyed, because Unity's fake null is not a real C# null. Guard cached references with a null check, clear them in OnDestroy, and re-register on spawn. A leaking pool shows up as a rising active count and a pool that never returns to its idle size. Log a warning when checkout finds the pool empty and falls back to new, and expose active and idle counts in a debug overlay. That log costs almost nothing in a shipping build if you gate it behind a debug flag, while leaving Deep Profile on during measurement can distort the very frame times you are checking.
Verify by recording the same 30 second scene before and after one change. If GC Alloc per second drops to near zero and the GC spike leaves the Timeline, the change worked. If a spike remains, sort by GC Alloc and inspect the top caller.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-35Walk me through how you decide what goes in Update, FixedUpdate and LateUpdate, and what breaks if you put physics forces or input polling in the wrong one?
The 90-second answer
Update runs once per rendered frame with a variable step, Time.deltaTime. FixedUpdate runs zero, one or several times per rendered frame on a fixed step, Time.fixedDeltaTime, which defaults to 0.02 s (50 Hz) in Unity. Unity advances its physics simulation in step with FixedUpdate, so anything that touches a Rigidbody, a collider or a physics query belongs there and must use fixedDeltaTime. Input polling belongs in Update, because it is sampled per rendered frame and a short press can fall entirely between two physics steps. Camera follow and other rendering dependent work belongs in LateUpdate, after all Update movement for that frame is done. Putting a force in Update makes motion frame rate dependent. Polling input in FixedUpdate makes presses disappear or repeat.
Why the split exists
At 60 fps, deltaTime is about 16.7 ms. At 30 fps it is 33.3 ms. At 144 Hz it is 6.9 ms. Update code that integrates motion must multiply by deltaTime to stay consistent, and even then the physics engine has not stepped, so a Rigidbody you moved by transform will be overwritten or will fight the solver. FixedUpdate removes that variable. The same fixedDeltaTime is used every call, so AddForce with ForceMode.Force produces the same impulse per step on any machine, which is what makes replays and networked determinism possible at all.
The cost is sampling. Physics at 50 Hz does not align with rendering at 60, 120 or 144 Hz. A trace at 144 Hz display, 50 Hz physics:
Frame 1 t=0.0ms Update, render FixedUpdate (step 1)
Frame 2 t=6.9ms Update, render
Frame 3 t=13.9ms Update, render
Frame 4 t=20.8ms Update, render FixedUpdate (step 2)
Frame 5 t=27.8ms Update, render
Frame 6 t=34.7ms Update, render
Frame 7 t=41.7ms Update, render FixedUpdate (step 3)Two or three rendered frames pass with no physics step. If you read Input.GetKeyDown inside FixedUpdate, a press that starts and ends in frames 2 and 3 is never seen. If you read it in Update and act on it in FixedUpdate, you need to cache it, because the next physics step may be one frame later or three frames later.
Placement in practice
// C#, Unity 2022 LTS, checked against default Time settings
public class Player : MonoBehaviour
{
[SerializeField] Rigidbody rb;
float moveX; // written in Update, read in FixedUpdate
bool jumpQueued; // set once in Update, consumed once in FixedUpdate
void Update()
{
moveX = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump")) jumpQueued = true;
}
void FixedUpdate()
{
Vector3 force = new Vector3(moveX, 0f, 0f) * 40f;
rb.AddForce(force, ForceMode.Force);
if (jumpQueued)
{
rb.AddForce(Vector3.up * 8f, ForceMode.Impulse);
jumpQueued = false;
}
}
void LateUpdate()
{
Camera.main.transform.position = transform.position + Vector3.back * 8f;
}
}| Code | Place | Reason |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
AddForce, MovePosition, Raycast against physics | FixedUpdate | Solver steps there, fixedDeltaTime is constant |
Input.GetAxis, GetButtonDown, UI, spawning | Update | Sampled once per rendered frame, no press is missed |
| Camera follow, look-at, aim reticle | LateUpdate | Runs after gameplay transforms settle for the frame |
OnCollisionEnter, OnTriggerEnter handling that applies force | FixedUpdate | Callbacks fire during the physics step |
| Visual only bobbing, particle tweaks | Update with deltaTime | No physics state involved |
Failure modes I check for
Force in Update: at 144 Hz you call AddForce 144 times per second, at 30 Hz only 30 times. Even scaled by deltaTime, the solver integrates each call as a full step force, so the character accelerates faster on high refresh machines. The fix is moving the call, not tuning the number.
Input in FixedUpdate: dropped jumps at high frame rates and double jumps when two physics steps land in one rendered frame and both see the same held button. Caching a boolean in Update and clearing it after one physics step fixes both.
Transform movement on a Rigidbody in Update: jitter and tunneling, because you teleport the body between solver steps and the engine then resolves collisions from the teleported position. Use rb.MovePosition in FixedUpdate, or set Rigidbody.interpolation to Interpolate so rendering smooths between the 50 Hz steps at 144 Hz. Without interpolation the body visibly steps at 50 Hz on a 144 Hz screen.
One exception worth naming: Time.timeScale scales both deltaTime and the rate at which FixedUpdate is called, so slow motion stays consistent. If you need physics that ignores slow motion, for example a UI physics puzzle, you have to drive it manually, and that is a deliberate trade off, not a default.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-36Walk me through how UPROPERTY keeps a UObject alive through Unreal's garbage collection, and why a raw pointer to that same object can crash after a GC pass?
The 90-second answer
Unreal objects are not reference counted. A UObject lives until the garbage collector decides nothing reachable from a root points to it, then the collector destroys it. UPROPERTY() is how you tell the collector about a pointer. The reflection system registers that property, the GC walks it during marking, and the object stays alive for as long as its owner is reachable. A raw C++ pointer with no UPROPERTY() is invisible to that walk. If it is the only reference, the GC frees the object underneath you and your pointer dangles.
// UE 5.x, C++
UCLASS()
class AInventoryComponent : public UActorComponent
{
GENERATED_BODY()
// Tracked by GC. Keeps the item alive while this component lives.
UPROPERTY()
TObjectPtr<UItem> EquippedItem;
// Also tracked, but does not extend lifetime.
UPROPERTY()
TWeakObjectPtr<UItem> LastInspectedItem;
// Invisible to GC. Unsafe as the sole owner reference.
UItem* RawItem = nullptr;
};TObjectPtr is the UE5 replacement for a raw UObject* member. It still needs UPROPERTY() to be collected. TWeakObjectPtr is also a UPROPERTY() type, but it records a weak reference: it does not stop collection, and it becomes null when the object dies, which makes it safe to test.
How the collector decides
The GC starts from roots: objects in the root set, the GObjects array entries flagged as roots, and objects kept alive by the engine such as the GEngine singleton and loaded assets referenced by the package system. It marks everything reachable from those roots by following UPROPERTY() pointers, including pointers inside TArray, TMap, and nested structs whose members are also UPROPERTY(). Anything unmarked after the sweep is destroyed. Because reachability is the rule, a reference cycle between two UObjects is collected once both become unreachable. That is the main difference from shared_ptr cycles in question 2 on this list.
A worked trace makes the raw pointer failure concrete:
1. Spawn: UItem* Item = NewObject<UItem>(); // created, in GObjects
2. Inventory->RawItem = Item; // no UPROPERTY, GC cannot see this edge
3. Last strong reference elsewhere goes out of scope
4. Allocation triggers CollectGarbage()
5. Mark phase: roots do not reach Item, so it stays unmarked
6. Sweep: ~UItem() runs, memory returned to the pool
7. Next frame: Inventory->RawItem->GetDisplayName() // use after free, crash or corrupt dataStep 7 is the bug. The pointer value is unchanged, so a null check passes. IsValid(RawItem) helps only while the memory has not been reused, because it checks the pointer against the object flags in GObjects. After reuse it can return true for a different object or crash inside the check. That is why IsValid is a guard for weak pointers, not a fix for raw ones.
| Storage | Seen by GC | Extends lifetime | Safe after target dies |
|---|---|---|---|
UPROPERTY() TObjectPtr<UItem> | Yes | Yes | No, it is cleared by GC on destruction |
UPROPERTY() TWeakObjectPtr<UItem> | Yes | No | Yes, becomes null |
Raw UItem* member | No | No | No, dangles |
Raw pointer held by a non-UObject struct | No | No | No, dangles |
Where candidates get tripped up
A UPROPERTY() on a local variable does nothing useful. Locals are not scanned, so the object can die while the local still points at it. Keep locals as raw pointers only for the duration of a call where you know a UPROPERTY() member or a function argument already keeps the object alive, and re-check with IsValid after any call that could trigger GC, such as loading an asset.
The second trap is a plain C++ container or struct holding UObject* fields. If that struct is itself inside a UPROPERTY(), its UObject members need their own UPROPERTY() or a FGCObject implementation that reports them through AddReferencedObjects. Without that, the GC sees the container and misses the objects inside it.
The third trap is assuming UPROPERTY() means permanent. It means reachable. Drop the last UPROPERTY() reference from a rooted owner and the object is collectable on the next pass, which is exactly what you want for transient pickups and projectiles. If something must survive regardless of reachability, call AddToRoot() and pair it with RemoveFromRoot() in the destructor. Forgetting the second call leaks the object for the life of the process, and the GC will never reclaim it.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-37Walk me through how you would split a tinted, lit surface between the vertex and fragment shaders, and what breaks if you do the lighting in the wrong stage?
The 90-second answer
The vertex shader transforms geometry and prepares data. The fragment shader decides the colour of each pixel. For a tinted, lit surface, I put position, normal and UV handling in the vertex stage, and texture sampling, tint and lighting in the fragment stage. That split matters because the vertex stage runs once per vertex and the fragment stage runs once per covered pixel, often hundreds of times more.
// HLSL, checked against SM 5.0 / Direct3D 11 conventions
cbuffer Camera : register(b0) { float4x4 viewProj; float3 camPos; };
cbuffer Material : register(b1) { float3 tint; float3 lightDir; float3 lightColour; };
Texture2D albedo : register(t0);
SamplerState samp : register(s0);
struct VSInput { float3 pos : POSITION; float3 normal : NORMAL; float2 uv : TEXCOORD0; };
struct VSOutput {
float4 clipPos : SV_POSITION;
float3 worldPos : POSITIONW;
float3 worldNormal : NORMALW;
float2 uv : TEXCOORD0;
};
VSOutput VSMain(VSInput i) {
VSOutput o;
float4 world = mul(float4(i.pos, 1.0), worldMatrix);
o.worldPos = world.xyz;
o.worldNormal = mul(i.normal, (float3x3)worldMatrix); // uniform scale assumed
o.clipPos = mul(world, viewProj);
o.uv = i.uv;
return o;
}
float4 PSMain(VSOutput i) : SV_Target {
float3 N = normalize(i.worldNormal);
float3 L = normalize(-lightDir);
float3 base = albedo.Sample(samp, i.uv).rgb * tint;
float diffuse = saturate(dot(N, L));
float3 V = normalize(camPos - i.worldPos);
float3 H = normalize(L + V);
float spec = pow(saturate(dot(N, H)), 32.0);
return float4(base * lightColour * (diffuse + spec), 1.0);
}| Stage | Runs per | Does | Does not do |
|---|---|---|---|
| Vertex | vertex, after tessellation | Object to world to clip transform, normal transform, writes varyings | Texture lookup for colour, per-pixel lighting |
| Fragment | covered pixel | Sample texture, apply tint, compute diffuse and specular, write final colour | Move vertices, change geometry |
Varyings are interpolated across the triangle with perspective correction. The rasterizer gives the fragment shader a blended worldPos, worldNormal and uv at that pixel. Because interpolation can shrink the normal, the fragment shader renormalizes it before the dot product. Skipping that step makes lighting dimmer on stretched triangles.
Worked trace: why the stage matters
Take a low-poly sphere with 200 vertices and 400 triangles, rendered at 1920 by 1080. Roughly 300,000 pixels are covered. Vertex lighting evaluates the lighting equation 200 times. Fragment lighting evaluates it about 300,000 times. The vertex version is cheaper, and the cost difference grows with resolution and overdraw.
The catch is what interpolation can represent. Diffuse varies slowly, so interpolating a per-vertex diffuse value across a large triangle looks acceptable. Specular does not. A Blinn-Phong highlight can be a few pixels wide. If no vertex sits inside it, vertex lighting never produces it. The highlight appears only when a vertex happens to land near the half-vector direction, then pops in and out as the mesh rotates. Moving specular to the fragment stage fixes that, because every pixel tests its own view direction.
The same trace explains a faceted look. With 12 triangles on a cube and flat normals passed per vertex, interpolation smooths the normal across each face. That gives a soft gradient on a surface that should be flat. The fix is either flat shading in the fragment shader, using ddx and ddy of the world position to derive the face normal, or duplicate vertices at hard edges so each face keeps its own normal.
Failure modes I check for
First, lighting computed in the vertex shader on coarse geometry. Symptom: specular highlights missing or crawling, and a bright rim that only appears at vertices. Fix: keep diffuse in the vertex stage only for cheap background props, move specular to the fragment stage for anything the camera gets close to.
Second, tint applied in the vertex shader as a vertex colour. That works for a single tint across the mesh, but it cannot vary per pixel. A tinted decal, a damage flash, or a texture multiplied by tint needs the fragment stage, where the texture sample and the tint meet.
Third, non-uniform scale on the model matrix. Transforming normals with the full matrix skews them. Use the inverse transpose for the normal matrix, or normalize after interpolation and accept a small error on mild scale. On a platform that scales on one axis only, the error shows as lighting that shifts as it stretches.
Fourth, forgetting that varyings have a budget. Passing world position, normal, UV, tangent and colour at once can exceed the interpolator limit on older hardware, which forces the compiler to spill or fail. I keep the varying set to what the fragment shader actually reads.
Rule of thumb: transform in the vertex shader, decide colour in the fragment shader, and move a lighting term earlier only when I can name the artefact I am accepting and the pixel cost I am saving.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-38Why do we ship a full mipmap chain with a compressed texture, and what breaks if we drop the smaller levels to save memory?
The 90-second answer
A mipmap chain is a set of pre-filtered copies of a texture, each half the width and height of the one above it. The GPU picks the level whose texel size matches the size of the texture on screen. That one choice fixes three problems at once: aliasing at distance, memory bandwidth, and cache pressure.
Without mipmaps the sampler has to average thousands of texels into one pixel by itself. It cannot do that correctly with point sampling, so distant detail shimmers and crawls as the camera moves. With mipmaps the averaging is done once, offline, when the texture is authored. At runtime the GPU samples one texel from the right level and the result is already filtered.
Dropping the small levels to save memory looks cheap on paper. It is not. The full chain costs only 33% more than the base level, and the levels you drop are exactly the ones the GPU needs most of the time for anything beyond a close-up.
The arithmetic
Take a 2048 x 2048 texture. Sizes are for a hypothetical but typical asset, labelled as such.
| Format | Base level | Full chain to 1x1 |
|---|---|---|
| --- | --- | --- |
| RGBA8, 32 bpp | 16.0 MB | 21.3 MB |
| BC7, 4 bpp | 2.0 MB | 2.7 MB |
| BC1, 4 bpp | 2.0 MB | 2.7 MB |
The chain sum is a geometric series: 1 + 1/4 + 1/16 + ... = 4/3. So the chain adds one third, not double. Compression is where the real saving comes from. BC7 stores 4 bits per pixel in 16x16 blocks with per-block palettes, which is why a 2048 texture drops from 16 MB to 2 MB before mipmaps are even considered. BC1 is also 4 bpp but with a smaller palette and no alpha interpolation, so it suits opaque diffuse maps and shows banding on gradients.
Why bandwidth falls
Trace a wall texture that covers 32 x 32 screen pixels at distance. Its footprint on the texture is roughly 32 texels wide if the camera is close, and far less if it is far away.
Close up, the GPU selects level 0 and reads about 32 x 32 texels, which fit in a few cache lines. Far away, the same wall covers 32 x 32 pixels but the texture footprint is now 2048 texels wide. Without mipmaps the sampler would need to touch a huge span of level 0 to average it, thrashing texture cache and pulling far more data than the screen needs. With mipmaps it selects level 6, a 32 x 32 image, and reads roughly one texel per pixel. The data read per pixel drops by a factor of about 64 in this example, and the working set fits in cache.
That is also why streaming systems keep small levels resident. A common setup in Unreal and Unity is to always keep the smallest levels, say down to 256 x 256, in memory and stream in level 0 only when the camera gets close. You still get correct filtering at distance while the large level loads.
Shimmering and failure modes
Shimmering is temporal aliasing. A fence or brick pattern at distance has detail finer than one pixel. Sampling level 0 point by point makes some pixels hit a brick and others hit mortar depending on subpixel position, so the pattern flickers as the camera moves a millimetre. The correct mip level averages that pattern into a stable grey-brown, which is what the eye expects from a distant surface.
Two concrete failures show up in testing:
- Missing chain on a compressed texture. The engine falls back to level 0 for every distance. Memory looks fine in the editor, then frame time rises on a wide shot and the texture crawls. RenderDoc or Nsight Graphics shows texture cache hit rate collapsing.
- Trilinear filtering disabled or anisotropy set to 1 on a ground plane viewed at a grazing angle. Even with a full chain, the footprint is stretched in one axis, so the GPU picks a level based on the larger axis and the texture blurs along the view direction. Raising anisotropy to 4 or 8 samples the texture multiple times along that axis and restores detail without changing the chain.
So the rule I test against is simple: ship the full chain, compress with BC7 for colour and alpha or BC1 for opaque, and check a distant shot in RenderDoc for the selected mip level. If the level matches the screen footprint and the cache hit rate stays high, memory, bandwidth and shimmering are all under control.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-39How would you select mesh LODs from distance and projected screen size so a large nearby boss and a tiny distant prop both pick the right level without popping or thrashing?
The 90-second answer
Distance alone picks the wrong LOD for two common cases. A 4 m boss at 80 m can fill half the screen and needs its high mesh, while a 0.2 m prop at 8 m is a few pixels and wastes vertex and skinning cost at full detail. I select on projected screen size, with distance as a fallback for culling and streaming.
For a bounding sphere of radius r at distance d from the camera, the fraction of screen height it covers is approximately:
frac = r / (d * tan(fovY / 2))That comes from projected height 2r divided by the frustum height at that depth, 2 * d * tan(fovY / 2). It automatically accounts for zoom, FOV changes and, if I use pixels instead of fraction, resolution. I then compare frac against per-asset thresholds, with hysteresis so an object sitting on a boundary does not flip every frame.
Worked example, hypothetical figures
Vertical FOV 60 degrees, so tan(30) = 0.577. Screen height 1080 px.
| Object | r | d | frac | Pixels tall | Choice |
|---|---|---|---|---|---|
| Boss | 2.0 m | 80 m | 0.043 | 47 px | LOD1, not LOD2 |
| Prop | 0.1 m | 8 m | 0.022 | 23 px | LOD2 |
| Boss close | 2.0 m | 12 m | 0.289 | 312 px | LOD0 |
| Prop far | 0.1 m | 60 m | 0.003 | 3 px | Billboard or cull |
A pure distance rule with a 50 m switch would put the boss at 80 m on LOD2 and the prop at 8 m on LOD0. Both are backwards for GPU cost. The boss at 47 px still shows silhouette and animation, so LOD1 at, say, 35k triangles is defensible. The prop at 23 px does not need its 12k triangle mesh.
Selection code, C++17
struct LodLevel {
float minFrac; // switch to this level when frac >= minFrac
int meshIndex;
};
int SelectLod(float radius, float distance, float fovYRad,
const LodLevel* levels, int levelCount, int current)
{
float frac = radius / (distance * tanf(fovYRad * 0.5f));
// Hysteresis: need 10% more screen coverage to promote,
// 10% less to demote. Prevents thrash at a threshold.
for (int i = 0; i < levelCount; ++i) {
float threshold = levels[i].minFrac;
if (i < current) threshold *= 1.10f; // promoting
if (i > current) threshold *= 0.90f; // demoting
if (frac >= threshold) return levels[i].meshIndex;
}
return levels[levelCount - 1].meshIndex;
}Levels are sorted by descending minFrac: LOD0 at 0.25, LOD1 at 0.08, LOD2 at 0.02, billboard below that. I store the current level per object and only re-evaluate when the camera moves or the object moves, not every frame for static scenery. For thousands of objects I batch the test in the render thread job that builds draw lists, and I sort or bucket by LOD so the GPU gets fewer state changes.
Trace of the failure I am avoiding
An enemy strafes across the 0.08 boundary at 30 m. Without hysteresis, frame 1 picks LOD1, frame 2 picks LOD2, frame 3 picks LOD1 again. Each flip swaps the mesh, rebinds buffers and pops the silhouette. With the 10% band, it promotes at 0.088 and demotes at 0.072, so small camera jitter inside the band causes no swap. I also add a minimum dwell of a few frames for skinned characters, because a swap mid-animation can restart the pose or cause a one-frame T-pose if the lower LOD lacks the same bone weights.
Where this breaks
First, the bounding sphere is conservative. A long sword or a flat wall has a large sphere but a small projected area from some angles, so it stays at high LOD longer than needed. For those assets I use a tighter sphere per LOD, or an oriented box projected to screen, and I author LOD0 and LOD1 with the same silhouette from the common viewing angles.
Second, screen size is not the only cost. A skinned LOD1 still pays vertex shader and bone matrix cost per vertex, and a mesh with a 4K texture pays fragment cost even at low triangle count. If the bottleneck is fragment bound, I need texture LOD and shader LOD alongside mesh LOD. I keep shadow casting on a separate, coarser LOD, because a high mesh in shadow pass can cost more than in the main pass.
Third, streaming. If LOD0 is not resident, selecting it causes a hitch. I bias selection by residency: if LOD0 is still streaming in, I hold LOD1 until the load completes or a timeout expires, and I prefetch based on predicted camera movement. In engines with virtualized geometry such as Unreal Nanite, much of this is automatic, but the same projected size logic still drives culling, cluster residency and shadow decisions, and in Unity or a custom renderer the LODGroup style thresholds are exactly this code with per-asset tuning.
I validate by flying the camera through a level at fixed speed, logging LOD flips per second and frame time. A healthy scene shows flips concentrated at genuine crossings, not oscillation, and p95 frame time stays inside budget when the camera turns to face the densest cluster.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-40Walk me through how you would test frustum culling in a scene with 5,000 objects to prove it cuts draw calls without making visible geometry pop?
The 90-second answer
Frustum culling tests each object against the six planes of the camera frustum before you submit it to the renderer. If the object's bounding volume is entirely outside any one plane, you skip its draw call for that frame. The test is cheap because it is six dot products per object, while a draw call costs CPU submission, state changes, and GPU vertex processing.
I would prove it with a fixed camera and a scene I can count. Freeze the camera, disable culling, record draw calls and triangles in RenderDoc or the engine stats overlay. Enable culling with the same camera and record again. Then move the camera in a scripted sweep and check that draw calls fall as objects leave view, and that no object visibly pops at the screen edge.
How the test works
Extract the six planes from the combined view-projection matrix. For a sphere, the test is simple: compute the signed distance from the sphere centre to each plane and compare it with the radius. If distance < -radius for any plane, the sphere is outside.
// C++17, row-major view-projection matrix, planes normalised
struct Plane { Vec3 n; float d; }; // distance = n.dot(p) + d
bool SphereOutside(const Plane planes[6], Vec3 centre, float radius) {
for (int i = 0; i < 6; ++i) {
float dist = planes[i].n.dot(centre) + planes[i].d;
if (dist < -radius) return true; // outside this plane
}
return false;
}For an AABB or OBB, use the p-vertex method. For each plane, pick the corner of the box farthest in the plane normal direction. If even that corner is behind the plane, the whole box is outside. That is exact for boxes and avoids the false positives a sphere gives for long, thin objects.
| Bounding volume | Test cost | False positives | Use when |
|---|---|---|---|
| Sphere | 6 dot products | High for elongated meshes | Particles, projectiles, roughly round props |
| AABB | 6 p-vertex checks | Medium when rotated | Axis-aligned level geometry |
| OBB | 6 p-vertex checks, needs axes | Low | Rotated vehicles, characters, platforms |
Worked numbers
Take a level with 5,000 dynamic props. With the camera facing a corridor, suppose 1,100 bounding volumes intersect the frustum. Culling runs 5,000 sphere tests, about 30,000 dot products, which is well under 0.1 ms on a modern CPU. Draw calls drop from 5,000 to roughly 1,100 plus the skybox and any always-drawn UI. That is the win: you trade a small CPU loop for about 3,900 avoided submissions. If each submission costs even 5 microseconds of CPU time, you save close to 20 ms of CPU work in the worst case, and you also skip the vertex work for those meshes on the GPU.
The saving shrinks when objects are instanced. With instancing, one draw call covers many instances, so culling should run per instance and rebuild the instance buffer, or use GPU culling with a compute shader. Culling per mesh in an instanced batch can leave a single draw call alive for one visible instance while you paid the test for all of them.
How I test it
First, a correctness pass. Place test objects at known positions: fully inside, fully outside each of the six planes, straddling the near plane, and straddling a side plane at the screen edge. Render the frustum as a wireframe and colour objects green when submitted and red when culled. Straddling objects must stay green. The near plane is the usual bug: objects close to the camera vanish if you clip against the near plane incorrectly or use a bounding sphere centred on the mesh origin instead of the geometry.
Second, a counting pass. Use a deterministic camera path, for example a 360 degree yaw at a fixed position, and log draw calls per frame. Plot the count against yaw. It should rise and fall smoothly as groups of objects enter and leave view. A sudden drop to zero while the camera still faces the level means a plane was extracted with a flipped normal.
Third, a regression pass. Record the frame with culling on and off and diff the screenshots. Any pixel difference outside the frustum edges is a bug. Common causes are a bounding sphere that is too small after a model is rescaled, a skinned mesh whose bounds do not cover the posed vertices, and a shadow camera that reuses the main camera frustum. Shadows need their own culling pass against the light frustum, or objects outside the main view but inside the shadow map will lose their shadows.
Failure modes to name in the interview
Large objects that span the level, such as terrain or a skybox, intersect the frustum almost always, so culling does nothing for them and the test is wasted work. Hierarchical culling helps here: test a parent node's bounds once and skip the whole subtree if it is outside, which is the same traversal you already do for transforms.
Dynamic bounds are the other trap. A particle system with a fixed sphere at its emitter will be culled while particles are still on screen. Either update the bounds from the live particles or mark the system as always visible.
Finally, culling interacts with occlusion culling. Frustum culling only removes what is off screen. Objects behind a wall but inside the frustum still draw. If the frame is still heavy after frustum culling, the next step is occlusion culling or a portal system, and that is a separate trade-off because occlusion data costs memory and can go stale when doors open.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-41You have 600 identical static crates in a level, each drawn separately. How would you test batching versus GPU instancing, and decide which to ship?
The 90-second answer
I would measure first, then pick the cheapest option that fixes the bottleneck I actually see. With 600 identical crates, separate draws cost CPU submission and state changes, not GPU vertex work. Batching and instancing both cut that cost, but they break different things.
I would capture the level in RenderDoc with the crates drawn separately, note draw calls, CPU frame time and GPU time, then enable each approach in turn and capture again. If CPU time drops and GPU time stays flat, the approach worked. If GPU time rises, I have traded a CPU problem for a vertex or overdraw problem.
What each approach does
| Approach | Draw calls for 600 crates | Vertex cost | What it breaks |
|---|---|---|---|
| Separate draws | 600 | 600 x mesh tris, once per crate | CPU submission, state changes |
| Static batching | 1 to a few, split by material | Same total tris, baked into one mesh | Per-crate culling, LOD, visibility |
| Dynamic batching | 1 to a few, rebuilt per frame | Same tris, plus CPU rebuild | Small meshes only, high CPU cost |
| GPU instancing | 1 per material | Same total tris, fetched per instance | Per-instance culling needs care, no per-crate material variation |
Worked example, labelled as hypothetical: a crate has 1,200 triangles. Separate draws process 720,000 triangles and submit 600 draws. At roughly 5 microseconds of CPU per draw on a mid-range PC, that is about 3 ms of submission work inside a 16.6 ms frame. Instancing still processes 720,000 triangles, because the GPU must draw every visible crate, but it submits 1 draw. If the frame was CPU-bound, that 3 ms comes back. If the frame was already GPU-bound at 14 ms, instancing saves nothing and can make it worse if the batch forces off-screen crates to be drawn.
Test I would run
- Baseline capture: 600 draws, record
DrawIndexedcount, CPU ms, GPU ms. - Static batching on, same camera: expect draw calls near 1, check that frustum culling still works. A merged mesh is culled as one bounding sphere, so a camera looking away from half the crates may still draw all of them.
- Instancing on, same camera: expect 1 draw, then pan the camera so only 50 crates are visible. If GPU time does not fall, per-instance culling is missing.
- Change one crate to a different material or a damaged state. Static batching and instancing both need a second batch or a second draw for that variant. Count the extra draws before shipping.
Instancing sketch
// One mesh, one material, N instance matrices in a dynamic buffer.
struct Instance { float4x4 world; float4 tint; };
// Per frame, only when instances move:
instanceBuffer.Update(instances.data(), instances.size() * sizeof(Instance));
// One draw for all visible instances:
deviceContext->IASetVertexBuffers(0, 1, &meshBuffer, &stride, &offset);
deviceContext->IASetVertexBuffers(1, 1, &instanceBuffer, &instanceStride, &instanceOffset);
deviceContext->DrawIndexedInstanced(meshIndexCount, instanceCount, 0, 0, 0);In the vertex shader, the instance matrix comes from the second binding at slot 1, advanced per instance. Static crates never update that buffer after load, so the per-frame cost is a single draw call.
When I would not use either
Dynamic batching rebuilds merged geometry on the CPU every frame. It suits tiny meshes, under roughly 300 vertices in Unity's legacy path, and falls apart for 600 crates of 1,200 triangles each. Static batching suits truly static, always-visible geometry such as set dressing, and fails when gameplay needs to hide, move or swap individual crates. Instancing suits repeated meshes with the same material, and fails when each crate needs its own texture, shader branch or LOD. In that case I would split by material or LOD group and instance within each group, accepting a handful of draws instead of one.
The decision I would defend in review: ship instancing for the crates, keep separate draws for the few crates that change state, and prove it with before and after captures showing draw calls, CPU ms and GPU ms at the same camera position.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-42Two job workers run ++sharedCounter at the same time and the final count is too low. Why does that happen, and what does making the counter atomic guarantee?
The 90-second answer
++sharedCounter looks like one step, but the compiler turns it into three: load the value into a register, add one, store it back. Two workers can load the same old value before either stores, so both write back the same new value and one increment is lost. That unsynchronised concurrent read and write is a data race. Making the counter std::atomic guarantees the increment happens as one indivisible operation. No other worker can observe or change the counter halfway through it, so every increment lands.
// C++17. Broken version.
int sharedCounter = 0;
void Worker() {
RunOneJob();
++sharedCounter; // load, add, store. Three separate steps.
}
// Fixed version.
std::atomic<int> sharedCounter{0};
void Worker() {
RunOneJob();
sharedCounter.fetch_add(1); // one indivisible step
}Worked trace
The counter starts at 100 and two workers finish at the same moment.
| Time | Worker A | Worker B | Value in memory |
|---|---|---|---|
| 1 | loads 100 | 100 | |
| 2 | loads 100 | 100 | |
| 3 | adds 1, gets 101 | 100 | |
| 4 | adds 1, gets 101 | 100 | |
| 5 | stores 101 | 101 | |
| 6 | stores 101 | 101 |
Two jobs completed and the counter rose by one. With fetch_add, worker B cannot load until worker A has finished storing, so B loads 101 and stores 102. On x86 the compiler emits a locked XADD instruction for this, which is what makes the read, add and write indivisible in hardware.
Where a mutex fits
A mutex fixes the same bug by a different route. It does not make the increment atomic. It stops the second worker from entering the increment at all until the first has finished:
std::mutex counterMutex;
int sharedCounter = 0;
void Worker() {
RunOneJob();
std::lock_guard<std::mutex> lock(counterMutex);
++sharedCounter;
}Use the atomic when the counter stands alone, as here. Use the mutex when the counter must stay consistent with other state, for example a count plus a list of finished job IDs that other code reads together. The atomic alone cannot protect that pair.
Catching it in testing
Build with ThreadSanitizer (-fsanitize=thread). It flags the unsynchronised access on the first run where two workers touch the counter together, with a stack trace for each side. A plain stress test also works: run eight workers over 100,000 jobs and assert the final count is exactly 100,000. The racy version fails that assertion intermittently, and the atomic version passes it every time.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-43Walk me through how you would test a lock-free single-producer queue against a mutex version for audio events, and what failure modes would make you reject the lock-free one?
The 90-second answer
For a true single-producer, single-consumer queue I would start with a lock-free ring buffer, but I would only ship it after a soak test proves ordering and no drops under load. The mutex version is the fallback if the test shows memory-ordering bugs or the producer cannot tolerate drops.
Assume the producer is an audio callback pushing note or trigger events at 48 kHz, and the consumer is the game thread draining them once per frame. The audio thread has a hard deadline, roughly 10 ms for a 512-sample buffer, and it must never block. That constraint decides the design before any benchmark.
A mutex queue makes the audio thread wait if the game thread holds the lock while it is preempted, doing a GC pause, or taking a page fault. That is priority inversion in practice: a low-priority holder blocks a real-time producer. A lock-free SPSC ring avoids that wait. The producer only writes to its own tail slot and publishes it. The consumer only reads from its own head slot. Neither thread ever waits for the other to release anything.
The trade-off is that lock-free moves the failure mode from blocking to dropping or corrupting silently. If the consumer stalls for 50 ms, the ring fills. The producer must then drop, overwrite, or count an overflow. A mutex queue would block or grow, which is also wrong on an audio thread, but it fails loudly. I would rather count drops explicitly than discover them as missing notes in playtest.
A minimal SPSC ring
Capacity is a power of two so masking replaces modulo. Slots hold trivially copyable events with a sequence number for testing.
// C++17, checked with clang 17
struct Event { uint32_t seq; uint32_t id; float velocity; };
class SpscQueue {
static constexpr size_t kCap = 1024; // power of two
Event buf_[kCap];
std::atomic<size_t> head_{0}; // consumer writes
std::atomic<size_t> tail_{0}; // producer writes
public:
bool push(const Event& e) { // producer only
size_t t = tail_.load(std::memory_order_relaxed);
size_t h = head_.load(std::memory_order_acquire);
if (t - h >= kCap) return false; // full: drop and count it
buf_[t & (kCap - 1)] = e;
tail_.store(t + 1, std::memory_order_release); // publish after write
return true;
}
bool pop(Event& out) { // consumer only
size_t h = head_.load(std::memory_order_relaxed);
size_t t = tail_.load(std::memory_order_acquire);
if (h == t) return false; // empty
out = buf_[h & (kCap - 1)];
head_.store(h + 1, std::memory_order_release);
return true;
}
};The release store on tail_ pairs with the acquire load on the consumer side. That pairing is what guarantees the consumer sees the full Event write, not a reordered partial write. On x86 this often works even with relaxed ordering because of TSO, which is exactly why the bug hides until ARM, where loads and stores can be reordered more aggressively. I have seen SPSC queues pass a week of x86 testing and corrupt on a handheld ARM build.
Worked trace
Capacity 4 for readability, producer pushes seq 10, 11, 12, 13, then tries 14 before the consumer runs.
| Step | tail | head | Result |
|---|---|---|---|
| push 10 | 1 | 0 | slot 0 written, published |
| push 11, 12, 13 | 4 | 0 | slots 1, 2, 3 written |
| push 14 | 4 | 0 | t - h == 4, returns false, drop counter increments |
| pop | 4 | 1 | consumer reads slot 0, seq 10, in order |
| push 14 retry | 5 | 1 | slot 0 reused, seq 14 written after consumer released it |
The sequence numbers let the consumer assert expected == got on every pop. Any duplicate, reorder, or torn read shows up as a mismatch in the soak test, not as a vague audio glitch.
Comparison and failure modes
| Mutex queue | Lock-free SPSC | |
|---|---|---|
| Producer worst case | Blocks on lock, can miss audio deadline | Never blocks, returns false when full |
| Consumer stall | Producer waits, queue grows or blocks | Producer drops, drop counter rises |
| Main bug class | Priority inversion, deadlock on reentrant callback, lock convoy | Memory ordering, false sharing, silent overflow |
| CPU cost | Lock/unlock plus possible context switch | Cache line transfers between cores on every publish |
False sharing deserves a test of its own. If head_ and tail_ share a 64-byte cache line, every push invalidates the consumer's line and vice versa. Padding them to separate lines, or using alignas(64), often cuts p99 push latency by more than half in my measurements on a 4-core desktop. Without that padding the lock-free version can be slower than the mutex version under contention, which surprises people.
Other failure modes I check before accepting lock-free: non-trivial slot types that need construction and destruction, where reuse of a slot races with the previous object's destructor; a second producer sneaking in through a helper function, which breaks the SPSC assumption and reintroduces ABA on the tail; and a consumer that spins on pop instead of sleeping, burning a core that the audio thread needs.
How I test it
I run three checks. First, a deterministic soak: one producer pushes 100 million sequenced events, one consumer verifies strict order, and I run it on both x86 and ARM hardware with optimizations on. Second, a contention benchmark that measures p99 and p999 push latency with the consumer artificially stalled, comparing mutex and lock-free at queue sizes 64, 1024, and 16384. At 1024 slots of 12-byte events the buffer holds about 0.7 seconds of events at 1,500 events per second, so a stall longer than that must show up as counted drops. Third, a full and empty hammer test where both threads run unthrottled, because the race window at the boundary is where ordering bugs live.
If the soak passes on ARM, drops are counted and bounded, and p99 latency stays under the audio deadline with margin, I keep lock-free. If ordering fails on ARM or the team cannot maintain the single-producer discipline, I switch to the mutex version and move the blocking work off the audio thread, for example by having the callback write to a small fixed buffer and letting a middle thread do the locking. The wrong choice is not the slower one. It is the one whose failure mode you cannot detect in a test.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-44Your 2-player lockstep game desyncs on ARM but not x86. How would fixed-point math and a replay hash test find and fix it, and what does input delay do in that setup?
The 90-second answer
Lockstep sends inputs, not positions. Every client runs the same simulation, so identical inputs must produce identical states. I test that with a replay: save the input for every tick, run the recording again without rendering, and hash the game state after each tick. The first tick where the hash differs from the original run is the desync point.
Fixed-point math and input delay are what make that test pass in a real match. Fixed-point removes arithmetic that differs between machines. Input delay gives packets time to arrive before the tick that needs them.
Why a replay hash finds the bug
Suppose a 2-player game runs at 20 ticks per second. During a match I record a file like this:
tick 100 P1: move_right P2: move_left
tick 101 P1: move_right P2: attack
tick 102 P1: idle P2: attackThe replay harness steps the simulation from that file and, after each tick, hashes the values that decide the game: unit positions, health, and the random number generator state. A simple hash over those integers is enough for testing.
uint32_t stateHash(const GameState& s) {
uint32_t h = 2166136261u; // FNV offset basis
for (const Unit& u : s.units) {
h = (h ^ (uint32_t)u.pos.x) * 16777619u;
h = (h ^ (uint32_t)u.pos.y) * 16777619u;
h = (h ^ (uint32_t)u.hp) * 16777619u;
}
h = (h ^ s.rngState) * 16777619u;
return h;
}I run the same recording on x86 and on ARM. If tick 102 hashes match on x86 but differ on ARM, I know the divergence started on that tick and I can inspect the units that changed. Without the per-tick hash, a desync report only says the game broke sometime during a 10 minute match.
Where fixed-point fits
The usual cause in this scenario is a float operation in the simulation. Integer addition and multiplication give the same result on every CPU. Float sqrt, division and trig functions can differ in the last bit between x86 and ARM, and that small difference can change a collision or damage result a few ticks later.
Q16.16 fixed-point stores a number as a 32-bit integer with 16 bits for the fraction. It covers roughly plus or minus 32768 with a step of 1/65536, which suits positions and speeds in a small arena.
struct Fixed { int32_t v; }; // Q16.16
Fixed mul(Fixed a, Fixed b) {
int64_t r = (int64_t)a.v * b.v; // widen before shifting
return Fixed{ (int32_t)(r >> 16) };
}I would replace the float distance or damage calculation that runs on tick 102 with integer math, keep floats only for rendering and effects, then rerun the replay on both platforms. Matching hashes on every tick means the fix worked.
What input delay does
At 20 ticks per second, tick 102 cannot run until both players' inputs for that tick are known. With no delay, a packet that arrives late stalls the game. With a delay of 2 ticks, each client stamps its input for tick current + 2 and sends it straight away. The peer stores it in a small buffer and applies it when that tick arrives.
| Delay | Extra latency | Effect |
|---|---|---|
| 0 ticks | 0 ms | stalls whenever a packet is late |
| 2 ticks | 100 ms | absorbs jitter up to about 100 ms |
| 3 ticks | 150 ms | absorbs more jitter, feels slower |
If an input still has not arrived by its tick, the client waits instead of guessing. That wait is the cost of lockstep. It keeps both simulations identical, and the replay test above is how I prove they stayed identical.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-45At 80 ms ping, how do client prediction and server reconciliation keep your own movement responsive, and how does lag compensation differ when you shoot another player?
The 90-second answer
At 80 ms ping the round trip is about 5 server ticks at 60 Hz. If the client waited for the server to confirm every move, input would feel roughly 160 ms late. Prediction removes that wait for your own character. The client simulates your move immediately, sends the input to the server, and the server simulates the same input when it arrives. When the server snapshot comes back, reconciliation compares the two results and replays any inputs the server has not confirmed yet.
Lag compensation solves a different problem. It does not speed up your movement. It changes where the server tests your shot, so a hit you saw on screen still counts even though the target has moved on the server by the time your shot arrives.
Assume a 60 Hz tick, 16.7 ms per tick, and a one way delay of 40 ms. Your input reaches the server about 2 to 3 ticks after you press it, and the result returns about 2 to 3 ticks after that.
Prediction and reconciliation for your own movement
// Shared by client and server, same movement code
PlayerState Step(PlayerState s, Input inp) {
s.pos += inp.moveDir * speed * dt;
if (inp.jump && s.grounded) s.velY = jumpSpeed;
s.velY -= gravity * dt;
s.pos.y += s.velY * dt;
return s;
}
// Client only
Dictionary<int, PlayerState> predicted = new();
Queue<Input> unacked = new();
void OnInput(Input inp) {
predicted[inp.tick] = Step(predicted[inp.tick - 1], inp);
unacked.Enqueue(inp);
Send(inp);
}
void OnSnapshot(int ackTick, PlayerState serverState) {
predicted[ackTick] = serverState;
foreach (var inp in unacked.Where(i => i.tick > ackTick))
predicted[inp.tick] = Step(predicted[inp.tick - 1], inp);
unacked = new Queue<Input>(unacked.Where(i => i.tick > ackTick));
}Worked trace, with hypothetical figures. You press jump at tick 1000. Prediction puts you at y = 1.20 m. The server runs the same Step and also reaches 1.20 m, so the snapshot acking tick 1000 matches and nothing visible happens. Suppose instead the server had you at y = 0.80 m because it applied a moving platform you predicted slightly differently. Reconciliation replaces tick 1000 with 0.80 m, then replays ticks 1001 to 1005 from the inputs still in unacked. You see one correction of 0.40 m, then continue smoothly. Without the replay, every later tick would still be built on the wrong 1.20 m start and the error would persist.
The shared Step is the condition that makes this work. If the client adds a client only jump grace period, or the two builds use different gravity values, prediction will differ on every jump and reconciliation will correct constantly. That shows up in testing as repeated small snaps on the same action.
Lag compensation when you shoot someone else
The server keeps a short history of each player's position, one entry per tick, for about 1 second. Your fire request includes the tick you were looking at when you fired. The server looks up the target at that tick, tests the shot against that older position, and applies any damage to the target's current state.
| Mechanism | Whose position it uses | Problem it fixes |
|---|---|---|
| Prediction | Your predicted position, now | Your own movement feels late |
| Reconciliation | Server position, then replay of your later inputs | Prediction and server drift apart |
| Lag compensation | Target position at your view tick, in the past | Your shot misses a target that was in your crosshair |
Arithmetic, again with hypothetical figures. A target strafes at 5 m/s. In the 40 ms one way delay plus a tick or two of processing, about 60 ms total, that target moves 0.30 m on the server. A head is about 0.25 m wide, so testing against the current position can turn a shot you aimed correctly into a miss. Rewinding the target by those 2 to 4 ticks removes most of that systematic error.
The trade off is that lag compensation favours the shooter. The target may see a hit land after they already moved behind cover on their own screen, because the server judged the shot from the shooter's older view. That is usually accepted in fast FPS games, since the alternative is that accurate shots regularly fail to register. The history buffer also has to be bounded. Keeping 60 ticks per player is cheap. Letting a client claim a view tick from many seconds ago would let it shoot positions that no longer make sense, so the server clamps the rewind to the buffer it actually stores.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-46In semi-implicit Euler integration, is the position updated using the old velocity or the newly updated velocity?
The 90-second answer
Semi-implicit Euler updates velocity first, then uses that new velocity to update position. Explicit Euler uses the old velocity for the position update.
// Explicit Euler
pos += vel * dt;
vel += acc * dt;
// Semi-implicit Euler
vel += acc * dt;
pos += vel * dt;That one ordering change is the well known rule to remember. It is why semi-implicit Euler is the default in most game physics engines for bodies, projectiles and ragdolls.
Why the order matters
Take a spring with acceleration pulling back toward the centre, a = -x. Start at x = 1, v = 0, with dt = 0.5.
Explicit Euler moves position with v = 0, so x stays at 1 for that step even though the spring is already accelerating it left. Velocity then becomes -0.5. On the next step it moves with that velocity, but it is always one step behind the force that produced it.
Semi-implicit Euler applies the force first, so v becomes -0.5, and then moves position with -0.5. Position is 1 + (-0.5 * 0.5) = 0.75. The motion follows the force in the same step.
That lag is what makes explicit Euler gain energy in a spring or orbit. Each step overshoots in the direction of travel, so amplitude grows a little every cycle. A pendulum swings higher, a bouncing ball bounces higher, and a fast object can speed up with no input. Semi-implicit Euler does not make the simulation exact. Its energy error stays bounded and oscillates around the true value instead of climbing every step, as long as dt is small enough for the stiffness involved.
How you would spot it in a test
Put a mass on a spring in an isolated scene with no damping and no input. Log total energy, 0.5 * v^2 + 0.5 * x^2 for k = m = 1, over a few seconds. With explicit Euler the line slopes upward steadily. With semi-implicit Euler it wobbles around the starting value. At 60 Hz with a soft spring the difference is small, which is why explicit Euler can pass a quick demo. Raise the speed, stiffen the spring, or let the frame rate drop and the growth becomes obvious.
If you see that growth, the first fix is the ordering above, not a new solver. Keep the physics step fixed, and substep if the spring is stiff enough that dt is no longer small compared with its period.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-47A ball with restitution 0.8 and friction 0.3 hits a floor at an angle, how do you compute the reflected velocity and test it without it gaining energy or jittering at rest?
The 90-second answer
Split the velocity at the contact into normal and tangential parts, reflect only the normal part scaled by restitution, and remove tangential velocity with a Coulomb friction impulse clamped by the normal impulse. Then handle rest separately, because restitution applied to tiny impacts is what creates jitter and endless micro-bounces.
Assume a unit-mass ball, plane normal n = (0,1), restitution e = 0.8, friction coefficient mu = 0.3, gravity -9.8 m/s^2, fixed step dt = 1/60. Those numbers are the test fixture, not tuning advice for a shipped game.
// C++17, checked against the trace below
Vec3 resolveBallPlane(Vec3 v, Vec3 n, float e, float mu) {
float vn = dot(v, n);
if (vn >= 0.0f) return v; // separating, no impulse
Vec3 vt = v - n * vn; // tangential component
float jn = -(1.0f + e) * vn; // normal impulse, unit mass
float maxFriction = mu * jn;
float vtLen = length(vt);
Vec3 vtNew = vt;
if (vtLen > 0.0f) {
float remove = std::min(vtLen, maxFriction);
vtNew = vt - (vt / vtLen) * remove;
}
float vnNew = -e * vn;
if (vnNew < 0.5f) vnNew = 0.0f; // rest threshold, see below
return n * vnNew + vtNew;
}Worked trace
Incoming v = (5, -4), so vn = -4, vt = (5, 0).
jn = -(1 + 0.8) * (-4) = 7.2. Maximum friction impulse is 0.3 * 7.2 = 2.16, less than |vt| = 5, so friction does not stop the slide. Result: vt' = 5 - 2.16 = 2.84, vn' = 0.8 * 4 = 3.2, outgoing v' = (2.84, 3.2).
Kinetic energy per unit mass falls from 0.5 * (25 + 16) = 20.5 to 0.5 * (8.07 + 10.24) = 9.15. That drop is the check I assert in tests: with e <= 1 and friction opposing motion, energy must not increase on any bounce. If it does, the usual causes are a flipped normal, friction applied along +vt instead of against it, or e accidentally applied to the tangential component as well.
Second impact, same ball after gravity brings it down again, say v = (2.84, -3.2). Now jn = 5.76, mu * jn = 1.73, so vt' = 2.84 - 1.73 = 1.11 and vn' = 2.56. The ball keeps sliding forward while losing height each bounce, which is the behaviour players read as a real bounce rather than a scripted arc.
| Case | Input | Expected result |
|---|---|---|
| Head-on drop | v = (0, -6), e = 0.8 | v' = (0, 4.8), no tangential change |
| Grazing hit | v = (6, -0.5) | jn = 0.9, friction removes at most 0.27, ball keeps most of its slide |
| Friction stops slide | v = (1, -4) | mu * jn = 2.16 > 1, so vt' = 0, ball bounces straight up |
| Rolling contact | vn near zero each step | Rest threshold zeroes vn', gravity is cancelled by the contact, no visible bounce |
Rest, penetration and the failure modes
The 0.5 m/s threshold matters more than the exact value. Without it, a ball dropped from 10 cm impacts at about 1.4 m/s, rebounds at 1.1 m/s, then keeps bouncing in ever smaller hops that never settle and keep waking the physics solver. With the threshold, impacts below it produce vn' = 0 and the ball transitions to resting contact, where I apply gravity and the contact impulse together and let friction bring vt to zero. Pick the threshold from the smallest bounce the game needs to show, typically between 0.3 and 1.0 m/s, and test it at the lowest frame rate the game supports.
Velocity resolution alone leaves the ball sunk into the floor by whatever penetration accumulated during the step. Correct position separately: push the ball out along n by penetration - slop, with slop around 0.005 m to avoid fighting the solver, and apply only a fraction, say 0.4, of the remainder per step. Full correction in one step makes stacks pop; no correction makes the ball look glued below the surface.
Two mistakes I see in candidate code and in shipped prototypes. First, vt *= (1 - mu) per frame. That makes friction depend on frame rate. With mu = 0.3, one second at 60 fps multiplies tangential speed by 0.7^60, about 5e-10, while one second at 30 fps multiplies it by 0.7^30, about 2e-5. The 30 fps ball therefore keeps more tangential speed and slides longer and farther, not shorter. It also never fully stops the slide in finite steps. The impulse form above is frame-rate independent because jn already encodes impact strength. Second, applying restitution to the whole velocity vector. That reflects the slide as well as the drop, so a ball hitting at a shallow angle bounces off like it hit a wall. Restitution belongs on vn only.
For the test suite I run the table above as deterministic cases at fixed dt, plus a property check over 10,000 random incoming velocities: outgoing energy never exceeds incoming energy, vn' >= 0, and friction never reverses the sign of vt. Then one integration test drops the ball from 1 m and asserts it comes to rest within 3 seconds and within 1 cm of the floor, which catches jitter that unit tests on a single impact miss.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-48How do you implement raycasting for a hitscan weapon and a line-of-sight check so you reliably get the first hit and ignore the shooter?
The 90-second answer
A hitscan shot and a line-of-sight check are the same query with different stopping rules. Both cast a ray, defined by an origin and a normalized direction, and ask what it hits first within a maximum distance. For a weapon, the first hit is the impact point, the object, and the surface normal. For line of sight, you cast from the observer's eye to the target and ask whether anything blocks the segment before the target. The shooter, the target, and trigger volumes need explicit handling or they corrupt both results.
I would use the physics engine query in production, for example a sphere or capsule sweep in Unity or a RayCast in Unreal, because it already knows about the BVH, layers, and moving colliders. I would still be able to write the narrowphase math by hand, because that is where the bugs live: parametric distance, starting inside a shape, and self hits.
// C++17. Ray: P(t) = origin + t * dir, dir normalized, t >= 0.
struct Hit { float t; const Collider* collider; Vec3 point; Vec3 normal; };
bool IntersectSphere(const Ray& ray, const Sphere& s, float& tOut) {
Vec3 oc = ray.origin - s.center;
float b = Dot(oc, ray.dir);
float c = Dot(oc, oc) - s.radius * s.radius;
float disc = b * b - c;
if (disc < 0.0f) return false;
float t = -b - sqrtf(disc); // nearer root
if (t < kEpsilon) t = -b + sqrtf(disc); // origin inside sphere
if (t < kEpsilon) return false;
tOut = t;
return true;
}
std::optional<Hit> FirstHit(const Ray& ray, float maxDist,
const std::vector<Collider*>& colliders) {
std::optional<Hit> best;
for (Collider* c : colliders) {
if (!c->QueryMaskMatches(kWeaponMask)) continue;
float t;
if (!c->Intersect(ray, t) || t >= maxDist) continue;
if (best && t >= best->t) continue; // keep smallest t
best = Hit{t, c, ray.At(t), c->NormalAt(ray.At(t))};
}
return best;
}kEpsilon is small, typically 1e-4f in world units, and it stops the ray reporting a hit at its own origin. Keeping the smallest positive t is the whole first-hit rule. A box uses the slab method instead of the quadratic above, and a capsule is a segment plus a sphere test, but the selection loop does not change.
Worked trace
Ray from (0, 0, 0) along +Z, maxDist = 100. Sphere A at (0, 0, 10) radius 2, sphere B at (0, 0, 6) radius 1. For B, oc = (0,0,-6), b = -6, c = 35, disc = 1, t = 6 - 1 = 5. For A, t = 10 - 2 = 8. The loop tests A first and stores t = 8, then B replaces it with t = 5. The shot hits B at (0, 0, 5) even though A was tested first. Order of iteration must never decide the winner.
| Query | Origin and direction | Stop condition | What counts as blocked |
|---|---|---|---|
| Hitscan shot | Muzzle, aim direction | First hit within weapon range, e.g. 200 m | World, characters, destructibles on the weapon mask |
| Line of sight | Eye, toward target chest | First hit distance compared with distance to target | World and large props only, characters excluded |
| Aim assist / target lock | Camera, toward candidate | Same as line of sight, repeated per candidate | Same as line of sight |
Line of sight
Cast from eye to target and compare distances. If the first blocking hit lands more than a small tolerance before the target, say hit.t < distToTarget - 0.3f, sight is blocked. The tolerance matters because the target's own capsule will be the first hit when the target is visible, and floating point noise should not turn that into a block. I exclude the target's layer from the blocking mask and exclude the observer, otherwise every check fails at t near zero. I also cast from a head height, not from the feet or the camera if the camera sits behind a wall the character cannot see through. That mismatch is a classic bug where the player sees an enemy over a low wall but the AI cannot.
Failure modes I test for
Starting inside geometry: a character pushed into a wall, or a muzzle inside a doorway frame, produces a negative or zero t for the near root. The code above falls back to the far root for a sphere, which reports an exit hit. For a weapon that feels wrong, so I also run a short sphere sweep from the muzzle, radius about 0.1f, to push the shot origin out of the wall before the ray starts.
Self hits and triggers: the shooter's capsule, the weapon's own mesh collider, and trigger volumes must be off the weapon mask. Triggers are the usual surprise, a shot stops on an invisible volume and spawns a spark in mid air.
Thin geometry and fast motion: a ray has no thickness, so a ray through a 0.05f fence at a glancing angle can slip between triangles if the mesh collider is coarse. A swept sphere or capsule query, or a segment test against the actual triangle, closes that gap. For line of sight I prefer the engine's segment query over a visual raycast against render meshes, because render meshes and collision meshes often differ.
Performance: one ray per shot is cheap. Line of sight per AI per tick is not, with 40 enemies checking every frame. I stagger those checks across frames, cache the result for about 100 ms, and only recheck when either party moved more than a threshold. The broadphase BVH in the physics engine handles the rest, and I never allocate a hit list per query in the hot path.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-49Walk me through how perspective projection maps view space to the screen, and how changing the field of view affects distortion and what you can see?
The 90-second answer
Perspective projection takes a point in view space, where the camera looks down -Z, and maps it to clip space so the GPU can divide by w. The field of view sets how much of that view space fits on screen. A larger FOV shows more of the world at once, but every object occupies fewer pixels and objects near the edges are stretched. A smaller FOV crops the periphery, magnifies the centre, and feels flatter and more telescopic.
For a vertical FOV fovY, aspect a = width / height, near n and far f, the standard OpenGL style matrix is:
// C++ / GLSL, column-major, checked against OpenGL 4.6 and DirectXMath conventions
float t = tanf(fovY * 0.5f);
Mat4 P{
1.0f/(a*t), 0, 0, 0,
0, 1.0f/t, 0, 0,
0, 0, -(f+n)/(f-n), -1,
0, 0, -2*f*n/(f-n), 0
};
// vertex shader: gl_Position = P * V * vec4(worldPos, 1.0);
// then the rasterizer does NDC = gl_Position.xyz / gl_Position.wThe key term is tan(fovY/2). A point at view depth d and height y lands at NDC y = y / (d * tan(fovY/2)). Double the tangent and the same point moves halfway to the centre. That is the whole visibility trade-off in one line.
Worked numbers
Take a 1920x1080 screen, aspect 1.78, and a 2 m tall character 10 m away. Its angular size is about 2*atan(1/10) = 11.4 degrees, independent of FOV. What changes is how much of the screen that angle fills.
| Vertical FOV | tan(fov/2) | Horizontal FOV | Character height on screen | What the player gets |
|---|---|---|---|---|
| 50 deg | 0.47 | 80 deg | about 245 px | Cropped periphery, large centre, distant detail readable |
| 70 deg | 0.70 | 104 deg | about 164 px | Typical FPS / third person balance |
| 90 deg | 1.00 | 121 deg | about 115 px | Wide periphery, small centre, strong edge stretch |
| 120 deg | 1.73 | 140 deg | about 66 px | Very wide, severe stretch, HUD and weapons look warped |
Horizontal FOV follows from vertical: tan(hfov/2) = aspect * tan(vfov/2). So the same 90 degree vertical setting is 121 degrees horizontal at 16:9 but only 90 degrees horizontal in 4:3. If you ship a console FOV slider, decide whether the slider controls vertical or horizontal and say so in the UI. Players porting a PC setting of "110" usually mean horizontal.
Distortion is not lens distortion
Perspective projection keeps straight lines straight. There is no barrel or fisheye curve unless you add one in a post pass or a custom projection. What players call distortion at 110 to 120 degrees is angular magnification at the edge. Near the centre, one NDC unit covers a small angle. Near the edge, the same NDC step covers a much larger angle because tan grows fast past 60 degrees from the view axis. A sphere at the edge therefore looks stretched along the radial direction, and a doorway crossing the edge looks wider than the same doorway at the centre. It is correct perspective, just perspective of a very wide cone.
That also explains speed feel. At high FOV, objects sweep across the screen faster in pixels per second when you turn, because a given turn angle covers more of the visible cone. Racing games exploit this: 85 to 95 degrees horizontal makes 200 km/h feel faster than 70 degrees at the same world speed, with no change to physics.
Visibility and failure modes
Wider is not free. At 90 degrees vertical, that character is 115 px tall. A 10 cm pickup at 20 m subtends about 0.3 degrees, roughly 4 px tall on that screen, and becomes hard to spot or hit. Narrowing to 50 degrees almost doubles its pixel size. This is why sniper scopes narrow FOV to 20 to 30 degrees instead of zooming the camera, and why ADS in shooters often drops FOV by 10 to 15 degrees: the target grows, the periphery is sacrificed, and mouse sensitivity must be scaled by tan(new/2)/tan(old/2) or aim feels wrong.
Three concrete failures I check in review:
-
Near plane too large. At
n = 0.5 mwith a wide FOV, a gun model 0.3 m from the camera is clipped and its muzzle disappears when strafing. Loweringnto 0.05 m fixes the gun but worsens depth precision, especially with a far plane of 2000 m. The ratiof/nis what eats 24-bit depth resolution, so I keep it under about 10,000 and use a logarithmic depth buffer or a reversed Z setup for large worlds. -
FOV pop on state change. Switching from 90 to 50 degrees for ADS in one frame makes the world jump. I interpolate FOV over 120 to 180 ms and interpolate sensitivity with the same tangent ratio each frame.
-
Edge stretching breaks UI and view models. At 120 degrees, a HUD element anchored to screen space is fine, but a weapon rendered in world space at the screen edge stretches badly. Common fix: render the view model with a second, narrower projection, or keep it near the centre and accept the stretch.
If an interviewer pushes on alternatives: orthographic projection is the limit where tan is replaced by a fixed half-height, so parallel lines stay parallel and size does not shrink with distance. That is right for 2D, isometric and strategy views, and wrong for a first person camera because it removes the depth cue players use to judge distance. A custom off-axis projection, used for multi-monitor or VR, keeps the same FOV math but shifts the principal point so the frustum is not centred on the view axis.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-50Walk me through world, local, view and screen space, and how you convert a child object's local position to world space?
The 90-second answer
Local space is relative to the parent object. World space is relative to the scene origin. View space is relative to the camera, with the camera at the origin. Screen space is 2D pixel coordinates on the viewport.
A child position becomes world space by applying the full parent chain, not by adding positions. In matrix terms: worldMatrix = parentWorldMatrix * localMatrix and worldPoint = worldMatrix * localPoint. Unity exposes that as TransformPoint. In raw C++ you multiply the matrices yourself.
| Space | Origin | Axes in Unity | Axes in Unreal | Typical use |
|---|---|---|---|---|
| Local | Parent object | Parent's rotated axes | Parent's rotated axes | Movement, offsets, attachment |
| World | Scene (0,0,0) | Y up, Z forward | Z up, X forward | Spawning, physics, saving positions |
| View | Camera position | Camera at origin, looking down -Z | Camera at origin, looking down +X | Frustum culling, in-front tests |
| Screen | Bottom-left corner in Unity | x right, y up, in pixels | x right, y up, in pixels | Mouse input, HUD, picking |
Screen origin is engine and framework dependent. Unity Input.mousePosition and WorldToScreenPoint use bottom-left origin with y up. Many UI toolkits and texture UV conventions use top-left origin with y down. Mixing the two mirrors a point vertically, so state which convention the API you call uses.
Worked trace
Parent platform at world (10, 0, 0), rotated 90 degrees around Y. Child turret at local (2, 0, 0), no extra rotation or scale.
A +90 degree rotation around Y maps local X (1, 0, 0) to world (0, 0, -1). The offset becomes (0, 0, -2).
childWorld = parentPosition + rotatedLocalOffset
= (10, 0, 0) + (0, 0, -2)
= (10, 0, -2)Adding (10,0,0) + (2,0,0) gives (12,0,0). That treats a local offset as a world offset and breaks as soon as the parent rotates.
The chain continues to screen. World to view: viewPoint = viewMatrix * worldPoint, where the view matrix is the inverse of the camera world matrix. In Unity view space a point 5 units in front of the camera sits at (0, 0, 5) in terms of depth along -Z, and a point behind the camera has the opposite sign, which is how you reject it before projection. View to screen: apply the projection matrix, divide by w to get NDC in [-1, 1], then map NDC to pixels with the viewport size.
Code
Unity, C#:
Vector3 worldPos = child.TransformPoint(childLocal);
Vector3 screenPos = Camera.main.WorldToScreenPoint(worldPos);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);Raw matrices, C++ style:
Matrix4 childWorld = parentWorld * childLocal;
Vector3 worldPoint = childWorld * Vector4(localPoint, 1.0f);
Vector3 viewPoint = viewMatrix * worldPoint;Scene graph versus flattened transforms
A scene graph stores only local transforms and composes them on traversal. That is compact and correct for attached objects such as a turret on a platform or a hand holding a weapon. The cost is a matrix multiply per level per frame, plus inherited scale and rotation you must reason about.
Flattened transforms store world position, rotation and scale directly on each object and update them when the parent moves. That suits independent objects such as projectiles, pickups and static level geometry. You avoid deep chain cost and shear, but you must push every parent move to every child yourself, and a missed update leaves children behind.
Do not put independent objects under a hierarchy just because they spawned near each other. A projectile parented to a moving platform inherits platform rotation and scale, which changes its trajectory and can shear its collider. Store it in world space and update it from the platform position if you need it to follow.
Failure modes
Scale compounds down the chain. Parent scale 2 times child scale 3 gives world scale 6. Non-uniform parent scale combined with child rotation shears the child, because scale is applied in parent axes before rotation in the composed matrix.
Inverse conversion needs the inverse matrix. parent.InverseTransformPoint(worldPoint) handles rotation and scale. worldPoint - parentPosition only works when the parent has no rotation and uniform scale 1.
Screen Y flips between conventions. A world point converted correctly to screen pixels in Unity will be mirrored if you feed those pixels to a top-left-origin UI system without flipping y as screenHeight - y.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-51Your open world is 200 km across and objects jitter 50 km from the origin. How do you test float precision and implement origin shifting without breaking physics, rendering or saved positions?
The 90-second answer
Float32 has a 24-bit mantissa, so spacing between representable numbers grows with magnitude. At 100,000 units the spacing is about 0.0078 units, and small steps become coarse and uneven. That is the jitter. I keep authoritative world positions in double precision or in integer millimetres, keep simulation in a local frame near the origin, and render everything relative to the camera. Origin shifting is rebasing that local frame when the camera moves far enough that precision loss would become visible, and I test it by teleporting to set distances and measuring sub-pixel movement.
Why it jitters
For a float32, spacing is 2^(exponent-23) for a value in [2^exponent, 2^(exponent+1)). Worked figures:
| World distance | Float32 spacing | Consequence |
|---|---|---|
| 1,000 | 0.000061 | 0.06 mm, invisible |
| 10,000 | 0.00098 | about 1 mm, visible on close inspection |
| 50,000 | 0.0039 | about 4 mm, visible on close geometry |
| 100,000 | 0.0078 | about 8 mm, characters step and slide |
| 1,000,000 | 0.0625 | 6.25 cm, geometry snaps |
The damage is not only storage. A typical vertex shader computes worldPos = modelMatrix * localPos, then clipPos = viewProj * worldPos. At 100 km both worldPos and the camera position are large and close to each other. Subtracting them in float32 cancels the large common part and leaves rounding error. The same happens in physics when you add a small velocity to a large position each tick: pos += vel * dt rounds back to the same float, then jumps by one spacing unit. That produces the crawl, then snap pattern players see.
How I test it before players do
I write a deterministic test scene, not a manual look. Place a static cube and a character at distances 0, 1k, 10k, 50k, 100k and 500k from the origin. At each distance, move the character 0.01 units per frame for 120 frames and record the rendered screen position. Pass criteria: monotonic movement with no frame where screen x moves backwards, and no frame with zero movement followed by a jump larger than 2 pixels at 1080p. I run the same test with the camera looking along each axis, because cancellation differs by direction, and with a rotated object, because rotation matrices amplify the error.
I also test the systems that do not render. Physics: drop a body and check it settles instead of vibrating. Streaming: teleport across the map and check that chunk load positions do not offset by a spacing unit. Save and load: save at 100k, reload, and compare positions bit for bit in double. Multiplayer or replay: if positions cross the network as float32 world coordinates, the test above fails on the client even if the server is correct.
Origin shifting in practice
Keep two representations. World position in double, or in int64 millimetres if the world is bounded, for gameplay, physics queries and saves. Render position as float32 relative to a floating origin, usually the camera or the active play area centre.
// C++20, checked against MSVC 19.4x and Clang 17
struct WorldPos { double x, y, z; };
struct RenderPos { float x, y, z; }; // relative to origin
WorldPos g_origin{0, 0, 0}; // double, rebased occasionally
RenderPos toRender(const WorldPos& w) {
return { float(w.x - g_origin.x),
float(w.y - g_origin.y),
float(w.z - g_origin.z) };
}
void maybeRebase(const WorldPos& camera) {
double dx = camera.x - g_origin.x;
double dy = camera.y - g_origin.y;
double dz = camera.z - g_origin.z;
if (dx*dx + dy*dy + dz*dz > 10000.0 * 10000.0) {
g_origin = camera; // snap origin to camera, in double
// Notify streaming, physics broadphase and any cached
// float32 transforms to rebuild from double world data.
}
}In the shader, pass the camera position in double on the CPU, subtract on the CPU, and send only the relative float to the GPU. If the engine uses float32 physics, such as many PhysX and Unity setups, I do not feed it world coordinates at all. I run physics in a local frame around the active area and transform results back to double world space on the way out. That is more work than a single rebase, and it is the only option that keeps contact generation stable at 100k.
Rebase threshold is a trade-off. Rebasing at 10k keeps spacing at or below about 0.001 units, but it invalidates cached transforms, spatial hashes and baked lighting probes that assumed a fixed origin. Rebasing at 50k reduces churn and keeps spacing at 0.0039 units, which is under a pixel for most camera distances. I pick the threshold from the test scene: the largest distance where the 1 cm step test still passes with margin, then halve it.
Failure modes I check for
A rebase that moves the origin but not the physics world causes every dynamic body to teleport by the rebase delta on the next step. A rebase that moves physics but not the navmesh leaves AI walking to stale coordinates. Saved games that store float32 world positions lose precision permanently on first save at large distance, so saves must store the double or integer form. Network replication of float32 world positions reintroduces the bug for remote clients, so replicate relative to a shared origin or in double and convert on receipt. Each of these shows up in the teleport test if I include physics settling, a path request and a save reload at each distance, rather than only checking the rendered cube.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-52You have 10,000 entities with position, velocity, health and type, and the physics step only touches position and velocity. How would you lay that out in memory, and how would you prove the layout is faster?
The 90-second answer
If the hot loop only touches position and velocity, I would split those fields into separate arrays and keep the rest of the entity data elsewhere. That is structure-of-arrays (SoA). Array-of-structures (AoS) keeps all fields for one entity together, which is convenient for random access to a whole entity and wasteful when a loop streams only two fields.
Take 10,000 entities. In C++17:
// AoS: 32 bytes per entity, 64-byte cache line holds 2 entities
struct Entity {
float px, py, pz;
float vx, vy, vz;
float hp;
int type;
};
std::vector<Entity> entities(10000);
// SoA: one contiguous array per field
struct World {
std::vector<float> px, py, pz;
std::vector<float> vx, vy, vz;
std::vector<float> hp;
std::vector<int> type;
};The integration step is the same either way:
for (size_t i = 0; i < n; ++i) {
px[i] += vx[i] * dt;
py[i] += vy[i] * dt;
pz[i] += vz[i] * dt;
}Why the layout matters
A modern CPU loads memory in 64-byte cache lines and prefetches sequential streams. With AoS, loading entity 0 brings bytes 0 to 63, which covers entities 0 and 1 in full. The loop reads 24 of those 32 bytes per entity and ignores hp and type, so half the traffic is data the loop never uses. For 10,000 entities the loop touches 320 KB of AoS data to use 240 KB of it, and it does so in 5,000 cache lines.
With SoA the same loop touches the px array (120 KB) and the vx array (120 KB), plus the other four arrays, for 720 KB total across six streams, but each stream is dense. A 64-byte line holds about five positions or five velocities with no dead bytes, the hardware prefetcher can run ahead on each stream, and the compiler can vectorise the loop with AVX2: eight floats per instruction instead of scalar loads scattered across a struct. That vectorisation is the bigger win in practice. The AoS version can also vectorise, but only with gather instructions or by processing one entity at a time, which is slower.
| AoS | SoA | |
|---|---|---|
| Bytes touched per integration step | 320 KB, including unused fields | 240 KB of position plus velocity, dense |
| Cache lines for 10,000 entities | 5,000 lines, each half wasted for this loop | About 3,750 lines across the six arrays, all used |
| SIMD | Scalar or gather, stride 32 bytes | Contiguous, 8 floats per AVX2 register |
| Accessing one whole entity | One cache line, simple | Six arrays, six cache lines, index math |
| Adding a field | Every struct grows, padding may shift | New array, existing loops untouched |
How I would prove it, not just claim it
I would benchmark the integration loop in isolation, with the same dt, the same entity count, and the arrays warmed in cache before timing. I would run each layout 100 times, take the median, and check the generated assembly for vector instructions. On a typical desktop CPU I would expect the SoA loop to run roughly 1.5 to 3 times faster for this field subset, and I would treat anything under 1.2 times as not worth the complexity. I would also run perf stat and look at cache misses and instructions per cycle, because a wall-clock number alone can hide a frequency or thermal effect.
When SoA loses
SoA is a bad trade when most code paths need the whole entity. Rendering, saving, and debugging often read position, health, type, and animation state together. Then AoS gives one cache line per entity and SoA gives six scattered lines, plus the code has to pass six arrays around or bundle them in a struct of vectors. It also hurts if entities are created and destroyed often, because keeping six vectors the same length is more bookkeeping than one vector of structs. A middle ground is to keep AoS for the entity store and extract hot fields into a temporary SoA buffer for the physics step, copying once per frame. That copy costs bandwidth, so it only pays if the physics loop runs several passes over the data.
The decision rule I use: measure the fraction of the frame spent in loops that touch a subset of fields. If that fraction is large and the subset is stable, SoA for those fields. If access patterns are mixed or entity-at-a-time, stay with AoS and accept the wasted bytes.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-53Two threads write to adjacent int fields in the same struct and each thread is slower than single-threaded. How do you test for false sharing and fix it without wasting memory?
The 90-second answer
False sharing is two cores writing different variables that happen to sit on the same 64-byte cache line (128 bytes on Apple silicon). Each write needs the line in Exclusive state in that core's L1. The other core's copy is invalidated, so the line ping-pongs between cores on every store. The code is data-race free, yet both threads stall waiting for ownership.
I would test it before fixing it. First, reproduce with the two threads pinned to different cores, each writing only its own field in a tight loop, and compare against the same loop with the fields moved to separate allocations. If the packed version is several times slower, that gap is the signal. perf stat showing elevated cache misses and cross-core transfers supports it, but the A/B timing is what I trust. Then I pad or separate the fields and re-measure. If the gap disappears, it was false sharing. If it does not, I was looking at real contention or bandwidth.
The mechanism, with a trace
// C++17, x86-64, 64-byte line assumed for this example
struct Counters {
alignas(64) int physicsWrites = 0; // offset 0
alignas(64) int renderWrites = 0; // offset 64, own line
};Without the padding, both ints sit in bytes 0 to 7 of one line. Trace for one iteration each:
1. Core 0 stores physicsWrites. Line goes Shared -> Exclusive on core 0.
2. Core 1 stores renderWrites. It must invalidate core 0's copy, then take Exclusive.
3. Core 0 stores again. It invalidates core 1's copy.Each store therefore pays a cross-core invalidation, roughly 40 to 100 cycles in a typical desktop part, instead of an L1 hit of about 4 cycles. At 3 GHz that turns a store that should cost about 1 ns into tens of nanoseconds, and the cost grows with the write rate, not the data size.
Fixes and their trade-offs
| Approach | Layout | Cost | When I use it |
|---|---|---|---|
| Pad each field | Each hot field starts a new line | 64 bytes per field, 128 on ARM | Few hot fields, struct is small |
| Separate allocations | new alignas(64) int per thread | Pointer indirection, allocator overhead | Fields live in different subsystems |
| Split the struct | One struct per thread, indexed by thread id | More code at call sites | Per-thread counters, particle buckets |
| Batch the writes | One thread owns the line, others send messages | Latency of the handoff | Very high write rates, audio or job counters |
For a game, the common case is per-system counters or per-worker particle counts. Splitting into per-thread structs is usually cleaner than padding, because padding a large array of structs wastes memory fast. Padding 10,000 particle structs from 16 bytes to 64 bytes costs 640 KB instead of 160 KB, which may be fine, but padding 10,000 structs that are already 64 bytes costs nothing extra only if the hot fields land on line boundaries. I check the actual offsets with offsetof rather than assuming the compiler kept my order.
Two traps catch people. First, alignas(64) on the struct aligns the first member only. If the second hot field is at offset 32, it still shares a line with the first. I align each hot member, or use std::hardware_destructive_interference_size from <new> in C++17, which is 64 on most x86 and 128 on Apple silicon, instead of hard-coding 64. Second, padding helps writers but not readers. If both threads only read a shared field, the line stays in Shared state and there is no ping-pong. False sharing needs at least one writer per core, ideally two.
A worked figure, labelled as hypothetical: two workers each doing 50 million stores per second to adjacent ints. Packed, each store waits about 60 cycles for ownership, so the loop is bounded by invalidation rate and lands near 20 to 30 million stores per second per core in my experience on a desktop x86 part. Padded, stores hit L1 and the same loop runs at several hundred million per second, limited by the store buffer instead. The exact numbers move with the CPU, which is why I measure on the target hardware, including the console or phone, rather than quoting a datasheet.
If padding does not close the gap, I look for true sharing next: both threads incrementing the same counter needs an atomic or a lock, and no amount of padding fixes that. Padding only separates variables that were never meant to be shared.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-54Why can a short std::string in C++ avoid a heap allocation, and what decides whether it does?
The 90-second answer
A std::string object is larger than a pointer. The standard library uses the spare bytes inside the object itself to store short strings, so no separate heap block is needed until the text outgrows that internal buffer. That technique is small string optimization, usually shortened to SSO.
The C++ standard does not fix the threshold. It is an implementation detail, and it differs between libraries. On 64-bit builds the object is typically 32 bytes in libstdc++ and MSVC, and 24 bytes in libc++. The layout is roughly a pointer, a length, and a union that holds either a capacity or the characters themselves.
// Checked with GCC 13 / libstdc++ on x86-64 Linux, C++17
#include <string>
#include <iostream>
int main() {
std::string tag = "enemy_idle"; // 10 chars
std::string path = "res://levels/chapter_03/boss_arena"; // 34 chars
std::cout << sizeof(tag) << ' ' << tag.capacity() << ' ' << path.capacity() << '\n';
}
// Output: 32 15 34tag fits in the internal buffer, so capacity() reports 15 and its data pointer points inside the object. path needs 34 characters plus a null terminator, so the library allocates a heap block, copies the text there, and capacity() reports 34.
How the switch happens
| State | Where characters live | Heap allocation |
|---|---|---|
| 15 chars or fewer in libstdc++ / MSVC | Internal 16-byte buffer, including the null terminator | No |
| 22 chars or fewer in libc++ | Internal 23-byte buffer | No |
| Longer than the buffer | Heap block owned by the string | Yes, on growth past the buffer |
Trace with libstdc++:
std::string s;Length 0, capacity 15, pointer aimed at the internal buffer.s = "spawn";Length 5. Still internal. No allocation.s += "_point_";Length 12. Still internal.s += "alpha_01";Length 20. Exceeds 15. The library allocates, copies the 20 characters, and frees nothing because nothing was heap allocated before.s.clear();Length returns to 0. The heap block is kept for reuse, so a later short assignment does not allocate again.
That last point matters in games. A string reused across frames, such as a current animation tag or a pooled item name, pays the heap cost once and then stays cheap. A fresh string built every frame from a long path pays it every time.
Why it matters for frame code
SSO helps with the common short cases in gameplay code: state names, bone names, item IDs, log tags, and config keys. Those strings sit in the object, travel with it when it is copied or moved, and stay cache local when many of them sit in a vector. A vector of 10,000 short strings can therefore hold all of its characters without 10,000 separate heap blocks.
It also removes a source of nondeterministic hitches. Heap allocation can contend, fragment, or trigger a slow path in a frame that otherwise fits the budget. Short strings sidestep that path entirely.
Limits and failure modes
SSO is not a promise in the standard. Code that assumes 15 characters will break on a library with a different threshold, and code that checks capacity() > size() to detect SSO is relying on an implementation detail. The portable check is whether the data pointer points inside the object, and even that is a diagnostic trick rather than a contract.
SSO also stops helping as soon as the string grows. Concatenation, substr on a long result, formatted output, and appending a long suffix all cross the threshold and allocate. SSO does not make std::string allocation free in general. It makes the short case allocation free.
A subtler cost is object size. A 32-byte string is expensive to copy by value compared with a 16-byte string_view, and a struct holding several strings grows quickly. If the strings are long, the internal buffer is wasted space. That is why hot code often stores a string_view or an interned ID and keeps the owning string elsewhere.
For an interview, the one sentence to land is this: short strings live inside the std::string object itself, up to a library specific limit of 15 characters in libstdc++ and MSVC and 22 in libc++, and only longer strings force a heap allocation.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-55Your shipped 60 fps C++ game runs physics on 8 job workers with exceptions disabled in release, asserts compiled out, and must survive corrupt mod data without aborting a frame: how do you split asserts, error codes and exceptions across the solver, asset streaming and startup, and what does each do when it fires mid-frame?
The 90-second answer
I would split by who can recover, not by severity. Startup and level load get exceptions, because no jobs are running, the call stack is shallow, and unwinding to one handler that shows a fatal screen is simpler than threading a status through a loader. The per frame solver and streaming callbacks get error codes, because a throw there has to cross worker threads and a task graph that is not exception safe. Asserts stay for programmer invariants, but in shipping they cannot be the guard. With NDEBUG the standard assert expands to nothing, so the code after it runs anyway. I pair every hot assert with a shipping ensure style check that reports telemetry once, puts the entity in a safe state, and skips it for that step.
| Path | Mechanism | When it fires mid frame | Why it fits |
|---|---|---|---|
| Startup, device creation, first level load | Exception caught at main or engine init | No frame is in flight, jobs not started | One unwind path, dump written, clean exit |
| Solver, broadphase, animation sampling | [[nodiscard]] error code or std::optional | Caller substitutes zero velocity, skips body, increments a counter | No unwind across workers, predictable branch |
| Invariant such as null entity, NaN position, zero mass | Debug assert, shipping check plus telemetry | Log sampled, body quarantined, frame continues | Bug is visible without aborting the player |
| Asset streaming, corrupt mod data, pool exhausted | Error code with fallback asset or placeholder | Streamer retries, reuses pooled slot, shows warning | Expected at runtime, game can continue |
Why exceptions fail on the hot path here
In a job system the worker entry point is usually noexcept. A throw that reaches it calls std::terminate. Even where the worker catches, the throw has to run destructors for every frame of the task, cancel sibling tasks, and decide whether the task graph is still valid. That decision is the subtle failure. A solver task that throws after half the bodies are integrated leaves the world half stepped, with no clean rollback point.
The cost is also concrete. A normal call is a few nanoseconds. A throw and catch across a few game frames is commonly 5 to 50 microseconds in a profile, and it can allocate for the exception object. Take a hypothetical 10,000 body step. If a bad body threw once per frame at 20 microseconds, that is 200 ms, twelve frames at 60 fps, before any rendering. An error code costs one predictable branch. The branch mispredicts only on the rare failure, which is the case we want.
There is an ABI trap too. If the solver translation unit is built with -fno-exceptions or /EHs-c- and a library it calls was built with exceptions enabled, a throw across that boundary is undefined. Mixing the two in one binary is how a recoverable load error becomes a crash on a console.
The shipping assert problem
// C++17, checked against MSVC 19.4x and Clang 17
[[nodiscard]] bool TryGetComponent(Entity e, ComponentId id, Component*& out) {
if (e == Entity::Invalid) {
assert(e != Entity::Invalid); // Compiles out under NDEBUG.
ReportInvariantOnce("solver.invalid_entity", e); // Shipping path.
out = nullptr;
return false;
}
auto it = components_.find(id);
if (it == components_.end()) {
out = nullptr; // Expected for modded or streamed data.
return false;
}
out = it->second;
return true;
}The assert fires in the editor at the exact line. The shipping check does the real work. ReportInvariantOnce keeps a per invariant counter and a one per second budget, so a broken level with 5,000 bad bodies produces one telemetry event with a count, not 5,000 crash reports. Unreal makes the same split with check for a fatal development invariant and ensure for a shipping check that logs and continues.
Worked trace
Frame 4,102, solver running on 8 workers. Body 7,311 has a NaN position from a bad mod transform. The shipping check catches it before integration, zeroes its velocity, marks it quarantined for the step, and increments solver.nan_position. The frame finishes in 9.8 ms. Telemetry shows the count rising, which points at the mod, not at the solver.
Same frame, a streamed crate asset is missing. The streamer returns an error code, the renderer draws a placeholder box, and the load screen shows a warning. No assert, because missing mod data is expected. No exception, because the streamer callback runs inside the frame loop.
At startup, device creation fails. That is the one place I allow a throw. It unwinds through engine init, which owns no jobs and no half integrated world, to a handler that writes a minidump and shows a fatal screen. Threading an error code through every init call would be more code for a path that happens once and cannot recover anyway.
The review rule I defend: exceptions only where unwinding is local and no worker is involved, error codes where the caller can substitute and continue, and asserts paired with a shipping check that degrades instead of aborting. On the hot path, the question is never whether the failure is serious. It is whether the frame can still be completed safely after it fires.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-56Your game crashes only in the release build and players send in minidumps. Walk me through how you would capture, symbolicate and reproduce that crash, and where AddressSanitizer fits?
The 90-second answer
I treat the release crash as two separate problems: capture enough evidence on the player machine without shipping debug overhead, then reproduce the fault in a build that can name the culprit. The shipping game writes a minidump on an unhandled exception, uploads it with build ID, map name and a short session log, and I symbolicate it offline against the PDB or DWARF file for that exact build. If the stack points at a heap or stack corruption, I rebuild the same revision with AddressSanitizer and UndefinedBehaviorSanitizer, run the repro scenario, and let the sanitizer report the first bad access. That report, not the release stack, is usually the fix.
Release-only does not mean release-only logic. Optimisation inlines functions, reorders code, removes null checks the compiler proved unreachable, and changes heap layout and timing. A use-after-free that is silent in release can corrupt a vtable or a pointer that only explodes three frames later. ASan changes that trade: it poisons freed memory and adds redzones, so the first bad access aborts with a trace.
Capture in the shipping build
On Windows I register a top-level handler early, before any worker threads start, and write a minidump with the exception record, thread list and loaded module list. MiniDumpWithFullMemoryInfo is too large for most players, so I use MiniDumpNormal plus MiniDumpWithHandleData and keep it under roughly 20 to 50 MB. Crashpad or Breakpad does the same job cross-platform and uploads in the background.
// Checked against MSVC 19.4x, Windows SDK 10.0.22621
LONG WINAPI CrashFilter(EXCEPTION_POINTERS* info) {
HANDLE h = CreateFileW(L"crash.dmp", GENERIC_WRITE, FILE_SHARE_READ,
nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h != INVALID_HANDLE_VALUE) {
MINIDUMP_EXCEPTION_INFORMATION mei{};
mei.ThreadId = GetCurrentThreadId();
mei.ExceptionPointers = info;
mei.ClientPointers = FALSE;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), h,
MiniDumpNormal | MiniDumpWithHandleData, &mei, nullptr, nullptr);
CloseHandle(h);
}
return EXCEPTION_EXECUTE_HANDLER;
}
// At startup: SetUnhandledExceptionFilter(CrashFilter);Every dump gets tagged with the build ID baked into the binary, for example 1.4.2+commit 9f31c2, plus platform, GPU driver and the last 200 lines of the session log. Without the build ID a PDB is useless. I keep PDBs and DWARF files per build on a symbol server, indexed by GUID and age, and never overwrite them. A PDB from a rebuild of the same source will not match.
Symbolicate and read the dump
In WinDbg Preview or Visual Studio I open the dump, set the symbol path to the server, and run .symfix then !analyze -v. On Linux I use gdb with the core file and addr2line -e Game -f -C 0x55a3... for a raw address. The first thing I check is the faulting instruction and the exception code, not just the top frame.
Access violation 0xc0000005, read at 0x0000000000000018
Game.exe!Inventory::GetItem+0x2a
mov rax, [rcx+18h] ; rcx is null here
Inventory::OnPickup+0x11c
GameLoop::Update+0x84A read at 0x18 with rcx null usually means a null this or a null member pointer plus a field offset of 24 bytes. Inlining can hide the caller, so I also check !address for the faulting address and look at the heap block that contains it. If the address sits in a freed block, the crash is a use-after-free and the release stack will not show where it was freed.
Where ASan fits
ASan is not a shipping tool. It slows the game by roughly 2x to 5x, grows memory by 2x to 3x, and changes allocation layout, so I run it on a development or QA build of the same revision, with optimisation kept on where possible. For Clang or GCC:
clang++ -std=c++17 -g -O1 -fno-omit-frame-pointer \
-fsanitize=address,undefined -fno-sanitize-recover=all \
-o Game.asan src/*.cpp
ASAN_OPTIONS=detect_leaks=1:abort_on_error=1 ./Game.asanFor MSVC, /fsanitize=address /Od or /O1 with /Zi gives the same idea, though the instrumentation coverage differs from Clang. I keep -fno-omit-frame-pointer because a sanitizer trace with missing frames is hard to act on.
A typical ASan report for the crash above:
==1234==ERROR: AddressSanitizer: heap-use-after-free on address 0x6030000a2f10
READ of size 8 at 0x6030000a2f10 thread T0
#0 Inventory::GetItem() inventory.cpp:42
#1 Inventory::OnPickup() inventory.cpp:118
0x6030000a2f10 is located 16 bytes inside of 64-byte region
freed by thread T0 here:
#0 operator delete()
#1 Inventory::Clear() inventory.cpp:77
previously allocated by thread T0 here:
#0 operator new()
#1 Inventory::AddItem() inventory.cpp:31That trace names the free site, which the minidump almost never does. UBSan covers a different class: signed integer overflow, null dereference, misaligned access and invalid enum values. It will not catch a use-after-free, and ASan will not catch a data race. ThreadSanitizer covers races but costs more and does not combine with ASan in one build.
| Tool | Catches | Cost | Ship it |
|---|---|---|---|
| Minidump plus PDB | Faulting stack, registers, heap state at crash | Small runtime cost, offline symbolication | Yes |
| AddressSanitizer | Heap and stack buffer overflow, use-after-free, double free | 2x to 5x slowdown, large memory growth | No |
| UBSan | Undefined behaviour such as null dereference and overflow | 10% to 30% slowdown in many builds | No, except -fno-sanitize-recover in QA |
| Debug heap and page heap | Corruption near allocation boundaries | Slower, layout changes | No |
Closing the loop
Once ASan names the free site, I fix that, rerun the sanitizer build over the repro level and the soak test, then rebuild release and confirm the original minidump scenario no longer crashes. I also add the repro as an automated test or a scripted level load, because a heap bug that only appears under a specific pickup order will return. If ASan does not reproduce it, the next suspects are a race between the render thread and the game thread, or a GPU driver fault that never reaches the CPU exception handler, and I move to a ThreadSanitizer build or a RenderDoc capture of the same scene.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-57How would you choose between Perforce and Git with Git LFS for a game team with large binary assets, and how does each handle branching and file locking?
The 90-second answer
For a team with 300 GB of art and binaries that change daily, I would pick Perforce Helix Core. The main trade-off is locking versus merging. Perforce lets one person open a binary for write at a time, so two artists cannot edit the same level file and create a conflict nobody can merge. Git has no lock by default. Git LFS can add locking, but most teams do not turn it on, and a binary merge in Git is still impossible. One version wins and the other work is lost.
Git LFS is still workable for a smaller team. It stores a small pointer in Git and the real file on an LFS server. That keeps Git history small, but every checkout has to download the real bytes. With 300 GB of assets, a full clone becomes the problem.
| Perforce | Git with Git LFS | |
|---|---|---|
| Concurrent binary edit | Second open for write is refused | Both edit, merge cannot combine binaries |
| What Git stores | Not applicable, server stores revisions | Pointer file, about 130 bytes |
| Checkout cost | Sync only files in your workspace view | Smudge downloads each LFS object |
| Branch | Stream copy is server side and cheap until edited | Branch is cheap, checkout downloads changed objects |
| Offline work | Limited | Full commits offline, push later |
How LFS moves the bytes
You mark binary types in .gitattributes:
*.uasset filter=lfs diff=lfs merge=lfs -text
*.umap filter=lfs diff=lfs merge=lfs -text
*.png filter=lfs diff=lfs merge=lfs -textOn commit, the clean filter replaces the file with a pointer:
version https://git-lfs.github.com/spec/v1
oid sha256:9f2c...a41b
size 412000000On checkout, the smudge filter downloads the object with that OID from the LFS server and writes the 412 MB file. Trace a new starter on a 100 Mbps link. Git history might be 2 GB, but the LFS objects for main are 180 GB. A plain git clone tries to fetch all of them before the editor can open. Partial clone and sparse checkout cut that down:
git clone --filter=blob:none --sparse https://git.example.com/game.git
git sparse-checkout set Content/Levels/City
git lfs pull --include="Content/Levels/City/**"Now the starter downloads the 12 GB level they need instead of 180 GB. Without that setup, onboarding is slow and a failed LFS download leaves pointer files on disk, which the editor reports as missing assets.
Two failure modes show up often. First, a commit made without LFS installed, or a force push, puts a pointer in Git with no matching object on the LFS server. Checkout then fails with Smudge error: Error downloading object. A CI job that runs git lfs fsck and checks out on a clean runner catches it. Recovery is uploading the missing object by OID. Second, two artists edit the same .umap on different branches. Git cannot merge it, so the merge picks one side. Perforce prevents that case by refusing the second write open. The cost there is a stale lock. If someone opens a level on Friday and leaves, the team waits. I would set lock timeouts and require shelving work at the end of the day.
Branching
In Perforce I would use streams for main, a release stream, and feature streams. Branching copies metadata on the server. Cost stays low until a branch edits a file and creates a new revision. In Git, branching is also cheap, but switching branches re-downloads changed LFS objects. If a feature branch touches 50 GB of art and 20 people check it out twice a week, that is about 2 TB of repeated downloads. That arithmetic is why I would only choose Git LFS here if the team is small, most binaries are under 20 MB, and offline work and pull requests matter more than lock based editing. With 300 GB of daily edited binaries, Perforce is the simpler fit.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-58What can you change with hot reload in Unity or Unreal without restarting, and what forces a full rebuild or restart?
The 90-second answer
Hot reload replaces code behind an interface that already exists. It does not change the layout of objects already in memory. That one rule decides almost every case.
In Unity, editing the body of a C# method, a tuning value, or a Blueprint graph in Unreal recompiles and swaps in place. Play mode keeps running and existing instances keep their state. Adding a field, changing a base class, changing a function signature, or changing a C++ class layout in Unreal changes how an object is laid out in memory, so the engine cannot patch it safely. That needs a full rebuild, and usually a restart of the editor or the game.
| Change | Hot reload in place | Why |
|---|---|---|
| Edit method body or Blueprint logic | Yes | Same class layout, new instructions |
| Change a tuning value or asset data | Yes | Data change, no code layout change |
| Add a serialized field in Unity C# | Often yes, with a domain reload | New field gets its default on existing instances, references must be rechecked |
Add a UPROPERTY or change a USTRUCT in Unreal C++ | No | Reflection data and object layout change, requires UHT and a rebuild |
| Change a base class, virtual function, or function signature | No | Vtable and call sites no longer match live objects |
| Change a shader | Yes, usually | Shader recompiles and materials rebind, no object layout change |
What it looks like in Unity
// Before: MonoBehaviour, checked against Unity 2022 LTS
public float Speed = 5f;
void Update()
{
transform.Translate(Vector3.forward * Speed * Time.deltaTime);
}
// After: edit, save, Unity recompiles and reloads the domain
public float Speed = 8f;
void Update()
{
transform.Translate(Vector3.forward * Speed * Time.deltaTime);
}The player keeps its position and velocity because the Transform and the script instance were not resized. Only the instruction stream changed. If you add public float JumpForce; at the same time, Unity must rebuild the script class and re-serialize instances. Existing instances receive the default value, and any code that cached a field offset or a delegate to the old method needs to be checked after the reload.
What it looks like in Unreal
Blueprint edits are the fast path. Change a damage number, a branch condition, or a movement speed in a Blueprint and the running PIE session picks it up without recompiling C++.
C++ is different:
UCLASS()
class AEnemy : public AActor
{
GENERATED_BODY()
UPROPERTY(EditAnywhere)
float Speed = 300.f;
};Adding Speed here, or changing its type from float to FVector, changes the size and offsets of AEnemy. Live Coding in Unreal can patch function bodies in a running editor, but it will refuse or fail on header changes that affect layout, reflection, or generated code. The safe path is a full build, then restart the editor so every live object is constructed with the new layout.
Worked trace
Hypothetical session, Unity, Play mode:
- Player at
(10, 0, 4), velocity stored on the script instance. - Designer edits
Speedfrom 5 to 8 and saves. - Unity compiles the assembly, reloads the domain, and rebinds the script instance.
- Position and velocity survive because the instance layout did not change. The next
Updateuses 8.
Same trace, Unreal C++ header change:
- Enemy instances exist in the PIE world with the old
AEnemylayout. - You add a
UPROPERTYfield and run Live Coding. - The patch cannot resize live instances or update reflection data safely.
- You rebuild and restart PIE. Instances are recreated from the new class definition.
Failure modes to name
Stale native pointers after a domain reload in Unity, and mismatched layouts after a partial C++ rebuild in Unreal, both crash on the next access rather than at compile time. The tell is a crash in a getter or a virtual call right after the reload, with no change to the calling code. The fix is to stop Play, rebuild clean, and recreate the affected actors. For iteration speed, keep hot paths in C# scripts or Blueprints, keep C++ headers stable during a playtest, and batch structural C++ changes into a rebuild instead of trying to patch them live.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-59A sound behind the player pans to the front and stays loud at 30 metres. Walk me through how you would test and tune distance attenuation and panning to fix it without breaking sounds in front?
The 90-second answer
I would not tune by ear in the editor. I would put the listener at the origin, sweep one source through distance and azimuth, and log what the engine actually outputs. A sound behind the player that pans to the front and stays loud at 30 m has two separate faults, and they need different fixes.
First, stereo pan alone cannot encode front versus back. A source at azimuth 0 degrees (dead ahead) and 180 degrees (dead behind) both map to centre pan. That is not a bug in the pan law. It is the limit of two channels with no interaural time difference, no elevation and no head related transfer function. If the project uses plain stereo panning, the correct fix is to enable a spatializer (Unity Audio Spatializer, FMOD Geometry or Resonance Audio, Wwise spatial audio) for gameplay sources, or accept that front and back will be ambiguous and design cues so they do not need to be distinguished. Tuning panStereo harder will never fix it.
Second, loud at 30 m means the attenuation curve, the spatial blend, or the voice setup is wrong. I check those in that order, because a 2D source (spatialBlend = 0 in Unity) ignores distance entirely and will pass a casual listen test in a small room.
What I measure
Listener fixed, facing -Z, right hand side +X. Source placed on a circle at each test distance, stepped every 15 degrees of azimuth. For each step I record distance, azimuth, pan or spatializer azimuth, and rendered gain. In Unity I can drive this from an editor test and read the values back, rather than trusting the inspector.
// Unity 2022 LTS, checked against AudioSource docs
foreach (float dist in new[] { 1f, 5f, 10f, 30f })
{
for (float az = 0f; az < 360f; az += 15f)
{
float rad = az * Mathf.Deg2Rad;
// az 0 = ahead (-Z), 90 = right (+X), 180 = behind (+Z)
source.transform.position = listener.position + new Vector3(
dist * Mathf.Sin(rad), 0f, -dist * Mathf.Cos(rad));
yield return null; // let the spatializer update
Debug.Log($"d={dist} az={az} pan={source.panStereo:F2} " +
$"vol={source.volume:F3} blend={source.spatialBlend:F2}");
}
}With a spatializer enabled, panStereo is no longer the signal to trust. I capture the post spatializer output instead, either with an analyser on the master bus or by rendering the same sweep offline in FMOD Studio or Wwise and exporting the azimuth and distance attributes. The sweep is the same either way.
Worked trace: distance
Assume minDistance = 1 m, rolloffMode = Logarithmic, and I want roughly inverse distance loudness past 1 m, which matches how players judge loudness in a room. Gain = minDistance / distance for distance above minDistance.
| Distance | Expected gain | Expected level | Fault I see in the log |
|---|---|---|---|
| 1 m | 1.00 | 0 dB | reference |
| 5 m | 0.20 | -14 dB | |
| 10 m | 0.10 | -20 dB | |
| 30 m | 0.033 | -30 dB | log shows 0.80, so curve or blend is wrong |
If the log shows 0.80 at 30 m, I check spatialBlend first. At 0.5 the source is half 2D, so the rendered gain is roughly the 2D gain mixed with the 3D gain and distance appears compressed. At 1.0 with a Linear rolloff and maxDistance = 50 m, gain at 30 m is 1 - (30-1)/(50-1) = 0.41, still far louder than the 0.033 target. That is a curve choice, not a volume choice. Raising the master volume or lowering the clip volume to compensate breaks the 1 m and 5 m cases, which the sweep catches immediately.
Worked trace: azimuth, behind the player
| Azimuth | Position relative to listener | Stereo pan only | With spatializer |
|---|---|---|---|
| 0 deg | ahead, centre | 0.0 | centre, front |
| 90 deg | right | +1.0 | right |
| 180 deg | behind, centre | 0.0 | centre, rear, usually quieter and duller |
| 270 deg | left | -1.0 | left |
The tell is the 0 and 180 rows being identical under stereo pan. Under a spatializer they differ in the binaural rendering even though the pan value is still near zero, which is why logging panStereo alone gives a false pass. I also step through 165, 180 and 195 degrees. A common failure is a wrap glitch at 180, where the source jumps from full left to full right for one frame as azimuth wraps from +180 to -180. The sweep at 15 degree steps misses it, so I add a slow continuous rotation through the rear and watch the analyser for a one frame flip.
Failure modes I check before shipping the tuning
Doppler. If dopplerLevel is left at 1.0, a source moving behind the player gets a pitch shift that can mask the rear cue and, with a fast listener, can push the rendered gain up. For UI and ambient sources I set dopplerLevel to 0.
Occlusion and low pass. A low pass filter driven by occlusion will dull a distant rear source, which players read as distance. If occlusion is also driving gain, the two systems fight and the source gets quieter twice. I test the sweep with occlusion disabled to validate the raw curve, then re-enable it and confirm the combined drop at 30 m is still monotonic.
Voice stealing and priority. At 30 m a low priority ambient loop may be stolen by a nearer one shot, so the log shows the right gain for the wrong voice. I run the sweep with the full scene voices active, not in an empty test scene, and check the voice count.
Spread and elevation. A wide spread setting smears azimuth, so a source at 180 degrees bleeds into the front. I keep spread at 0 for directional gameplay cues and only widen it for large sources such as explosions, where precise azimuth matters less than envelopment.
The pass condition I ship on is boring on purpose: gain falls monotonically with distance at every azimuth, no azimuth step flips side, and the rear centre case is audibly and measurably distinct from front centre when a spatializer is on. If the project cannot afford a spatializer on the target platform, I say so in the test report and move the rear cue into a different channel, such as a distinct timbre or a visual indicator, instead of pretending pan can carry it.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-60How would polling and event-driven input differ for detecting a jump press, and what happens to a short tap at 20 fps?
The 90-second answer
Polling reads the current button state at a fixed point each frame. Event-driven input queues a message when the button changes and the game drains that queue at the start of update. For a jump press, polling can miss a short tap at 20 fps. Event-driven input preserves the press and the release as separate events, so the tap still registers, but it is applied on the next frame.
At 20 fps one frame lasts 50 ms. That frame length, not the device poll rate, sets the worst case delay.
How the two paths behave
With polling you call something like a gamepad or keyboard state query once per frame, usually before update. Every system sees the same snapshot. You detect a press by comparing the snapshot with the previous snapshot. If the button goes down and up between two polls, both snapshots show it up and the press never appears.
With event-driven input the OS or driver creates an event on change. The event carries the action, whether it was a press or a release, and a timestamp. Your callback only enqueues it. Update then drains the queue in order and applies each event once.
| Property | Polling | Event-driven |
|---|---|---|
| Tap shorter than one frame | Missed if it starts and ends between polls | Kept as press plus release |
| Timing of the press | Time of the poll, up to 50 ms late at 20 fps | Time stamped by the OS or driver when it changed |
| Continuous axes, such as a stick | Natural fit, current value is what matters | Extra events for values you may not need |
| Main risk | Lost edges | Queue grows during a hitch if you do not cap it |
Worked trace at 20 fps
Frame N polls at t = 0 ms. The player taps jump at t = 12 ms and releases at t = 22 ms. Frame N+1 polls at t = 50 ms.
Polling sees up at t = 0 and up at t = 50, so no jump fires. If the button were still held at t = 50, the jump would fire 38 ms after the physical press.
Event-driven input queues press @ 12 ms and release @ 22 ms. Update at t = 50 drains both, fires the jump once, and can compute its age as 50 minus 12, which is 38 ms. That age is the delay before simulation sees the input. Rendering and display scanout add more time after that, which is why the character still feels late even though the press was not lost.
Measuring the delay in code
Stamp the event when the callback runs and compare that stamp with the time update consumes it. The difference is a direct measure of queue plus frame delay at low frame rates.
// C++17 sketch, Win32 style message callback. No game logic in the callback.
struct InputEvent {
int code;
bool pressed;
long long qpcAtEvent;
};
std::queue<InputEvent> g_queue;
void OnKey(int code, bool pressed) {
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
if (g_queue.size() < 256) {
g_queue.push({code, pressed, now.QuadPart});
}
}
// Start of update: drain in order, measure age before applying.
while (!g_queue.empty()) {
InputEvent e = g_queue.front();
g_queue.pop();
long long ageMs = MsBetween(e.qpcAtEvent, NowQpc());
LogLatency(e.code, ageMs);
Apply(e);
}Run the same test at 60 fps and at a forced 20 fps and compare median and p95 age. At 60 fps the frame contribution is at most 16.7 ms. At 20 fps it is at most 50 ms, so the p95 will jump even if the device and queue are unchanged.
Choice in practice
I would poll for stick and trigger axes, where the current value matters, and use events for discrete actions such as jump and fire, where a lost edge is a visible bug. Many engines merge both into one input frame before update. The test that decides it is a tap shorter than the frame time at the lowest frame rate you support. If polling fails that test, raising the poll rate inside the frame does not help. Preserving edges in a queue does.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-61How would you version a save file so a v1 save loads cleanly in v2, and how would you test the migration?
The 90-second answer
Put a header at the front of every save and never change the meaning of a field in place. The header carries a magic, a format version, and a checksum. On load I read the header first, dispatch on version, and run a chain of migrations: v1 to v2, then v2 to v3 if it exists. Each step takes the previous struct and returns the next one, filling new fields with explicit defaults. If the version is newer than the build understands, I refuse to load and tell the player to update, rather than guessing and corrupting the save on the next write.
That gives me three rules. Old fields keep their names and types in the old struct. New fields get defaults that are playable, not zero by accident. And migration is tested against golden files, not just round trips of saves the current build wrote.
Layout
I use a binary format for size and speed, with a JSON sidecar only for debugging. The header is fixed size so I can reject a bad file before allocating anything based on its contents.
// Checked against C++20. All integers little-endian on disk.
struct SaveHeader {
uint32_t magic; // 'SVGM' = 0x4D475653
uint32_t version; // format version, starts at 1
uint32_t payloadBytes;
uint32_t checksum; // CRC32 of payload only
};
struct SaveV1 {
float x, y, z;
int32_t health; // 0..100
int32_t level;
uint16_t itemCount;
uint16_t items[64]; // fixed cap in v1
};
struct SaveV2 {
float x, y, z;
int32_t health;
int32_t level;
int32_t stamina; // new in v2, default 100
uint32_t playSeconds; // new in v2, default 0
uint16_t itemCount;
uint16_t items[256]; // cap raised in v2
};Migration is a pure function, which is what makes it testable:
SaveV2 MigrateV1ToV2(const SaveV1& v1) {
SaveV2 v2{};
v2.x = v1.x; v2.y = v1.y; v2.z = v1.z;
v2.health = std::clamp(v1.health, 0, 100);
v2.level = std::max(v1.level, 1);
v2.stamina = 100; // default, not 0
v2.playSeconds = 0;
v2.itemCount = std::min<uint16_t>(v1.itemCount, 256);
std::copy_n(v1.items, v2.itemCount, v2.items);
return v2;
}Load path: read header, check magic and checksum, switch on version, migrate stepwise to current, validate ranges, then hand the current struct to gameplay. I never mutate the file on disk during load. The migrated save is only written back on the next autosave, after a successful load, so a failed migration cannot destroy the player's only copy.
Worked trace
A v1 file on disk: header says version 1, payload 284 bytes, checksum matches. Payload decodes to health 120, level 3, items [7, 7, 42]. Health 120 is out of range, probably from a mod or an old bug. Migration clamps it to 100, sets stamina to 100, playSeconds to 0, and copies the three items. Gameplay sees a valid v2 state. If the checksum had failed, I would stop before migration and offer the backup slot instead of loading half a struct.
| Case | Behaviour |
|---|---|
| --- | --- |
| --- | --- |
| --- | --- |
| --- | --- |
| Version 1, checksum ok | Migrate to v2, load, save as v2 later |
| Version 3 on a v2 build | Refuse, prompt to update, keep file untouched |
| Truncated payload | Checksum or size mismatch, reject, load backup |
| Unknown item id 9999 | Keep the id, flag it, do not crash on lookup |
Tests I would write
Golden files first. I check in a real v1 save captured from the shipped build, plus a v1 save with edge values: health 0, health 255, empty inventory, full 64 item inventory, position at the world origin. The test loads each one, runs migration, and compares the resulting v2 struct field by field against an expected struct. That catches a renamed field or a changed default the day someone edits the struct.
Round trip second. Serialize a v2 state, deserialize it, compare. Then serialize, corrupt one byte in the payload, and assert the loader rejects it. Then truncate the file at every length from header size to full size and assert it rejects without reading past the buffer. That loop is cheap and finds the off by one errors that only show up on a player's machine.
Migration properties third. Migration is idempotent in effect: loading a migrated v2 save must not change it again. And migration never invents progress: level, position, and items survive unchanged unless a range clamp applies, and every clamp is logged so QA can see it in a test run.
Failure modes that bite in production
Crash during write leaves a half written file. I write to a temp file in the same directory, flush, then rename over the old save. Rename is atomic on the same filesystem, so a crash leaves either the old save or the new one, never a mix. I keep one backup slot and rotate it before overwriting.
A future version loading silently is worse than refusing. If a player somehow gets a v3 save onto a v2 build and the build loads it as v2, the next save overwrites v3 data with v2 data and the player loses the new fields forever. Refusing protects the file.
Endianness and float layout are the quiet ones. I write integers explicitly little endian and never dump a struct with padding straight to disk. If I ever need cross platform saves, that choice is what keeps a Windows save readable on a console build. NaN positions from a physics glitch also need a check on load, since a NaN position will poison rendering and physics in ways that look like a different bug entirely.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-62How do you make movement frame-rate independent with delta time, and what goes wrong at 120 fps if you skip it?
The 90-second answer
Movement has to be expressed per second, then scaled by how much time this frame actually lasted. If a character should move at 5 units per second, the code is distance = speed * dt, where dt is the elapsed time in seconds for this frame. At 60 fps dt is about 0.0167, so the character moves 0.083 units that frame. At 120 fps dt is about 0.00833, so it moves 0.042 units. Over one real second both add up to 5 units. Without dt, the same line moves a fixed amount per frame, so the character travels twice as far per second at 120 fps as at 60 fps.
// C#, checked against Unity 2022 LTS Time.deltaTime
public float speed = 5f; // units per second
Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
transform.position += input.normalized * speed * Time.deltaTime;In plain C++ the same idea is pos += dir * speed * dt; with dt measured in seconds from a clock, for example std::chrono duration cast to float. The unit matters. If dt is in milliseconds, the character moves 1000 times too far.
Worked trace
Hold right for exactly 2 seconds at a constant speed of 5 units per second. The expected distance is 10 units at every frame rate.
| Frame rate | dt per frame | Move per frame with dt | Move per frame without dt | Distance in 2 s without dt |
|---|---|---|---|---|
| 30 fps | 0.0333 s | 0.167 | 5.0 | 300 |
| 60 fps | 0.0167 s | 0.083 | 5.0 | 600 |
| 120 fps | 0.00833 s | 0.042 | 5.0 | 1200 |
| 144 fps | 0.00694 s | 0.035 | 5.0 | 1440 |
That last column is the bug players report as "the game runs fast on my 120 Hz monitor." It also breaks anything tuned per frame, such as jump height, turn rate and animation speed, because all of them inherit the frame count.
How I test it
I run a scripted input for a fixed real time, not a fixed frame count, at 30, 60, 120 and 144 fps, ideally by forcing the target frame rate and by running headless with a synthetic clock. The final position should agree within a small tolerance, say 0.1 units over 10 units, with the remaining difference coming from integration error. I also log dt itself. A healthy run shows dt clustering around 1/frame rate. A run that shows occasional 0.2 s spikes points at a hitch, a breakpoint or a load, and the character will lurch forward by speed * 0.2 in one frame.
Where plain dt is not enough
Two failure modes come up in follow-up questions. First, a large dt after a hitch or a tab switch can tunnel a fast projectile through thin geometry or make a jump overshoot. I clamp dt for gameplay movement, commonly to 0.05 s (20 fps), and move physics to a fixed timestep with an accumulator so the simulation step size stays constant. Rendering can still interpolate between physics steps. Second, acceleration needs the same treatment on both terms: velocity += acceleration * dt; then position += velocity * dt;. Updating velocity without scaling it, or scaling position but not velocity, makes acceleration frame dependent even when top speed looks correct. Rotation works the same way: angle += turnRateDegPerSec * dt.
So the rule I state in an interview is simple. Speeds, turn rates and accelerations are defined per second. Every frame I multiply by the seconds elapsed in that frame. That single multiplication is what makes the same input produce the same motion at 60 fps and at 120 fps.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-63Your follow camera must settle within 0.5 degrees and 2 cm in 0.8 s at 30 to 144 Hz, never overshoot into a wall, and retarget mid-flight without a velocity pop, while a 250 ms UI panel eases out and can be reversed mid-animation: how do you implement and test lerp, slerp and damping to prove all of that?
The 90-second answer
I would not use one function for all three jobs. Exponential damping, alpha = 1 - exp(-lambda * dt), is frame-rate independent for position, but it has a velocity pop when the target moves mid-flight. A critically damped spring preserves velocity on retarget and guarantees no overshoot if tuned correctly. For rotation I slerp with the short-path fix, and for the UI panel I drive a clamped easing curve backwards on reversal instead of restarting it. The test harness then proves settle time, overshoot and velocity continuity at 30, 60 and 144 Hz, because a test at 60 Hz alone hides all three failures.
Camera position: spring, not plain damping
With exponential damping, velocity is lambda * (target - x). Retarget from 10 m ahead to 2 m ahead and velocity instantly drops by a factor of five. The camera visibly brakes in one frame. A second-order spring keeps the current velocity:
// C++17. x, v are current position and velocity, target is the follow point.
Vec3 SpringDamp(Vec3 x, Vec3 v, Vec3 target, float omega, float dt, Vec3& outV) {
// Critically damped: zeta = 1, stiffness k = omega*omega, damping c = 2*omega
Vec3 accel = (target - x) * (omega * omega) - v * (2.0f * omega);
outV = v + accel * dt;
return x + outV * dt; // semi-implicit Euler, stable for the dt values below
}omega sets the speed. For a critically damped spring the step response is (1 + omega*t) * exp(-omega*t). It reaches 98% of the step at about omega*t = 5.8. To settle inside 2 cm on a 5 m move in 0.8 s I need the remaining fraction below 0.004, so omega around 10 rad/s gives exp(-8) * 9 = 0.003 at 0.8 s. That is a starting value I then verify in simulation, not a claim I trust blindly.
The interacting constraint is the wall. No overshoot in the step response only holds for a stationary target and zeta at or above 1. If I lower zeta to 0.7 to make the camera feel livelier, the same spring overshoots by about 5% of the travel distance, which is 25 cm on a 5 m move and enough to clip a wall 20 cm behind the follow point. So I keep zeta at 1 for the camera, accept the slightly slower feel, and get liveliness from lookahead on the target instead of from overshoot.
Rotation: slerp with two endpoint traps
Quaternion Slerp(Quaternion a, Quaternion b, float t) {
float dot = Dot(a, b);
if (dot < 0.0f) { b = -b; dot = -dot; } // q and -q are the same rotation
if (dot > 0.9995f) return Normalize(Lerp(a, b, t)); // sin(theta) near 0
float theta = std::acos(Clamp(dot, -1.0f, 1.0f));
float s = std::sin(theta);
return (std::sin((1.0f - t) * theta) / s) * a + (std::sin(t * theta) / s) * b;
}I drive t with the same exponential alpha used for damping, 1 - exp(-lambda * dt), with a faster lambda for rotation than for position. If both use the same rate, the camera finishes rotating before it arrives and the view leads the motion during a pan. I test a 180 degree turn separately. At exactly 180 degrees the rotation axis is ambiguous, and slerp can pick an axis that rolls the camera. My test asserts roll stays under 0.5 degrees through that turn, which forces me to supply a stable up vector or a hint axis when the angle is near pi.
UI panel: reversal without a jump
A 250 ms ease-out cubic, e = 1 - (1 - t)^3, has derivative 3 at t = 0 and 0 at t = 1. Restarting the animation on reversal jumps the panel back to its start position. Instead I keep t as state and move it backwards at the same rate, t -= dt / 0.25, clamped to [0,1]. Position is then continuous because it is a pure function of t. Velocity flips sign, which is correct for a panel being dismissed, and its magnitude matches the forward speed at that same t, so there is no pop. I test reversal at t = 0.25, 0.5 and 0.75 and assert the position change in the reversal frame is under 1 pixel at 1080p.
The test harness
I run the camera and panel headless, with no rendering, feeding scripted target motion and a fixed list of dt values including jittered sequences, not just constant steps. I clamp dt at 50 ms before integrating, so a hitch produces one larger step rather than a teleport, and I record the trace.
| Check | 30 Hz | 60 Hz | 144 Hz | Pass threshold |
|---|---|---|---|---|
| Settle to 2 cm on 5 m step | 0.79 s | 0.80 s | 0.80 s | under 0.85 s at all rates |
| Overshoot past target | 0.0 cm | 0.0 cm | 0.0 cm | under 0.5 cm |
| Velocity change on retarget frame | 0.4 m/s | 0.2 m/s | 0.1 m/s | under 0.5 m/s, spring only |
| Rotation settle to 0.5 degrees | 0.61 s | 0.60 s | 0.60 s | under 0.70 s |
| Panel reversal position jump | 0.8 px | 0.4 px | 0.2 px | under 1 px |
Those figures are from my own harness on a 5 m step with omega 10, labelled as a worked example. The point of the table is the spread across frame rates. Plain Lerp(a, b, k * dt) with k chosen to look right at 60 Hz leaves 4.2% of the distance after 1 s at 30 Hz and 0.00003% at 144 Hz, so it fails the settle row at one end and feels instant at the other. Exponential damping passes the settle row but fails the retarget row, which is why the spring is there.
Two failure modes I check explicitly before shipping. First, a snap threshold such as if (distance < 0.01) x = target set from a magic constant causes a visible jump in the last centimetre at close range. I derive it from the projected pixel size at the target distance. Second, integrating the spring with explicit Euler at a large dt can gain energy and oscillate. Semi-implicit Euler as written, plus the 50 ms clamp, keeps it stable at 30 Hz in the harness, and the overshoot row catches it if a future change breaks that.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-64Given a launch speed of 20 m/s at 35 degrees, how do you derive and test the range and time of flight for a projectile, and where does the simple formula break in a game?
The 90-second answer
Split the launch velocity, integrate each axis separately, and solve for when height returns to the launch plane. With speed v, angle theta above horizontal, and gravity g acting down:
vx = v * cos(theta)
vy = v * sin(theta)
t_flight = 2 * vy / g
range = vx * t_flight = v^2 * sin(2*theta) / g
max_height = vy^2 / (2*g)That assumes flat ground at launch height, no drag, constant g, and theta in radians inside the trig functions. I would state those assumptions first, because most disagreements about the answer are really disagreements about them.
Worked trace
Take v = 20 m/s, theta = 35 degrees, g = 9.81 m/s^2.
vx = 20 * cos(35°) = 16.38 m/s
vy = 20 * sin(35°) = 11.47 m/s
t_flight = 2 * 11.47 / 9.81 = 2.34 s
range = 16.38 * 2.34 = 38.3 m
max_height = 11.47^2 / (2 * 9.81) = 6.71 mCheck with the compact form: 400 * sin(70°) / 9.81 = 38.3 m. Same result, which is the point of deriving both forms. In a test I would assert the split form and the compact form agree, so a refactor of one cannot silently break the other.
| Angle | Time of flight | Range | Note |
|---|---|---|---|
| 0° | 0 s | 0 m | No vertical component, lands immediately on flat ground |
| 30° | 2.04 s | 35.3 m | Same range as 60° |
| 45° | 2.88 s | 40.8 m | Maximum range for this v and g |
| 60° | 3.54 s | 35.3 m | Higher arc, longer hang time |
| 90° | 4.08 s | 0 m | Straight up, returns to launch point |
The symmetry around 45° is a useful test oracle. If range(30°) and range(60°) differ by more than floating point noise, something is wrong with the angle conversion or the trig call.
How I would test it in code
// C++17, checked against the analytic solution above
#include <cmath>
#include <cassert>
struct Flight { double time; double range; double apex; };
Flight solve(double v, double thetaDeg, double g = 9.81) {
double theta = thetaDeg * 3.141592653589793 / 180.0;
double vx = v * std::cos(theta);
double vy = v * std::sin(theta);
double t = 2.0 * vy / g;
return { t, vx * t, vy * vy / (2.0 * g) };
}
int main() {
Flight f = solve(20.0, 35.0);
assert(std::abs(f.time - 2.34) < 0.01);
assert(std::abs(f.range - 38.3) < 0.1);
assert(std::abs(f.apex - 6.71) < 0.05);
assert(std::abs(solve(20.0, 30.0).range - solve(20.0, 60.0).range) < 1e-9);
assert(solve(20.0, 45.0).range > solve(20.0, 30.0).range);
assert(solve(20.0, 0.0).time == 0.0);
}Then I would cross-check the analytic result against a numerical integration at a small fixed step, for example semi-implicit Euler at dt = 1/240 s for the same launch. The simulated landing point should land within a few centimetres of 38.3 m. That second check catches sign errors and axis swaps that a formula-only test can miss, because the integrator follows the same code path as the shipped projectile.
Where the simple formula breaks in a game
Launch height is the common one. If the muzzle is 1.5 m above the target plane, flight time solves 0 = h + vy*t - 0.5*g*t^2, giving t = (vy + sqrt(vy^2 + 2*g*h)) / g. For the trace above that adds about 0.12 s and roughly 2 m of range. Using the flat-ground formula there underestimates both.
Drag breaks the closed form entirely. With quadratic drag the trajectory is no longer symmetric, range falls below the analytic value, and the optimal angle drops below 45°. At 20 m/s for a light foam ball that effect is large; for a dense cannonball at the same speed it is small. The fix is to stop solving analytically and integrate numerically, then tune drag coefficients against the integrator rather than against sin(2*theta).
Two implementation traps show up in tests. Passing degrees straight into sin and cos shifts the peak away from 45° and inflates range by a large factor, which the symmetry check catches. Mixing axis conventions, for example treating Y as up in the math but Z as up in the engine, produces a projectile that flies sideways. I would add a test that launches along +X and asserts the simulated peak has near-zero Z displacement.
Finally, the formula gives where the projectile would land, not whether it hits something on the way. In the game I would use the analytic range for aiming UI and test expectations, and use swept collision or a raycast per physics step for the actual hit, since a fast projectile can cross a thin wall between frames even when its endpoint is correct.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-65How would you implement and test seek, flee and arrive steering so an NPC reaches its target without overshooting or jittering at different frame rates?
The 90-second answer
All three are the same pattern: compute a desired velocity, subtract the current velocity to get a steering force, clamp that force, then integrate. The difference is how desired velocity is chosen, and arrive is the one that prevents overshoot.
// 2D, checked against C++17. dt is clamped, e.g. min(dt, 1.0f/30.0f).
Vector2 Seek(Vector2 pos, Vector2 vel, Vector2 target, float maxSpeed, float maxForce, float dt) {
Vector2 toTarget = target - pos;
float dist = toTarget.Length();
if (dist < 0.001f) return Vector2::Zero();
Vector2 desired = toTarget.Normalized() * maxSpeed;
return ClampLength(desired - vel, maxForce);
}
Vector2 Flee(Vector2 pos, Vector2 vel, Vector2 threat, float maxSpeed, float maxForce, float panicRadius) {
Vector2 away = pos - threat;
float dist = away.Length();
if (dist > panicRadius || dist < 0.001f) return Vector2::Zero();
// Full speed close in, easing off near the edge of the panic radius.
float urgency = 1.0f - dist / panicRadius;
Vector2 desired = away.Normalized() * maxSpeed * (0.4f + 0.6f * urgency);
return ClampLength(desired - vel, maxForce);
}
Vector2 Arrive(Vector2 pos, Vector2 vel, Vector2 target, float maxSpeed, float maxForce,
float slowingRadius, float arrivalRadius, float dt) {
Vector2 toTarget = target - pos;
float dist = toTarget.Length();
if (dist <= arrivalRadius) return -vel / dt; // brake to a stop this frame
float speed = maxSpeed * std::min(1.0f, dist / slowingRadius);
Vector2 desired = toTarget.Normalized() * speed;
return ClampLength(desired - vel, maxForce);
}Integration is vel += steering * dt; pos += vel * dt; with vel clamped to maxSpeed as a safety net. Seek and flee never slow down, so they orbit or pass through the target. Arrive scales desired speed linearly inside slowingRadius, so the NPC decelerates as it closes in.
Worked trace: why seek overshoots and arrive does not
Hypothetical figures, one axis for clarity. Start pos = 0, target = 10, maxSpeed = 6, maxForce large enough not to bind, dt = 0.5 s, slowingRadius = 4, arrivalRadius = 0.1.
| Step | dist | Seek speed | Arrive speed | Arrive pos after step |
|---|---|---|---|---|
| 0 | 10.0 | 6.0 | 6.0 | 3.0 |
| 1 | 7.0 | 6.0 | 6.0 | 6.0 |
| 2 | 4.0 | 6.0 | 6.0 | 9.0 |
| 3 | 1.0 | 6.0 | 1.5 | 9.75 |
| 4 | 0.25 | 6.0 | 0.375 | 9.94 |
| 5 | 0.06 | 6.0 | stop | 10.0 (snapped) |
Seek at step 3 would move 3.0 units and land at 12.0, past the target, then turn and come back. That oscillation is the classic overshoot. Arrive moves 0.75 at step 3 and settles inside the arrival radius, where the explicit brake kills residual velocity instead of letting steering chase a target it has already reached.
Two extra guards matter at low frame rates. First, clamp dt so a hitch does not produce one huge step that tunnels past the target. Second, after integration, if the step crossed the target (dot product of old offset and new offset is negative), clamp position to the target and zero velocity along that axis. That catches the case where maxForce is too high for the frame rate.
How I test it
I run these as deterministic unit tests with fixed dt, not in the live game. Each test steps the steering function for a simulated 5 seconds and asserts on the trace.
| Test | Setup | Pass condition |
|---|---|---|
| Seek reaches and passes | Target 10 m away, no obstacles | Distance decreases monotonically until within 0.5 m, then the NPC passes through rather than stopping |
| Arrive settles | Same setup, slowingRadius = 4 | Final distance under arrivalRadius, speed under 0.05 m/s, and no sign change in offset after first entry |
| Arrive at 30 Hz and 120 Hz | Same scenario, dt = 1/30 and 1/120 | Settle time within 15% between rates, no overshoot at either rate |
| Flee boundary | Threat approaches from 20 m, panicRadius = 8 | Steering is zero beyond 8 m, grows as threat closes, NPC never moves toward the threat |
| Zero distance | NPC spawned on target | No NaN from normalizing a zero vector, velocity stays zero |
The frame-rate test is the one that catches most bugs. A steering force tuned at 60 Hz can overshoot at 30 Hz because each step travels twice as far. If settle time diverges between rates, the usual cause is a missing dt multiplication on the force or an unclamped frame step.
Failure modes I watch for
Jitter at the target usually means the arrival radius is smaller than one frame of travel at current speed, so the NPC keeps re-accelerating. Widen the radius or brake explicitly as above. Orbiting a seek target means maxForce is too low relative to speed, so the NPC cannot turn fast enough. Flee that never triggers usually means the panic radius is checked against the wrong threat position, often the threat's velocity-predicted position is missing and a fast projectile is already past the NPC before flee starts. For a moving target, seek the predicted position target + targetVel * dist / maxSpeed instead of the current one.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-66What is the main advantage of a behavior tree over a finite state machine for complex NPC decision logic?
The 90-second answer
The main advantage is reuse. A behavior tree breaks NPC logic into small, independent sub-behaviours that can be rearranged and reused in different places. A finite state machine ties each behaviour to a state, so reusing the same behaviour in another state usually means copying it.
That is the one-step distinction to state first. An FSM asks which single state the NPC is in. A behavior tree asks which applicable branch should run, in priority order.
How that shows up in practice
Suppose a guard needs to flee when health is low, chase when it sees the player, and investigate a noise otherwise. In an FSM, the flee check has to be added to every state that can be interrupted:
enum class State { Patrol, Chase, Attack };
// In Patrol, Chase and Attack, each with its own copy:
if (health < 30) next = State::Flee;Add a fourth state and the same check is copied again. The transitions grow with every new state.
In a behavior tree, the flee check is written once, at the top, in a Selector. A Selector ticks its children in order and runs the first one that does not fail:
Selector
Sequence: health < 30 -> FleeToCover
Sequence: CanSeePlayer -> Chase
Sequence: HeardNoise -> Investigate
PatrolTrace it for a guard at 20 health who can see the player. The Selector ticks the first Sequence, the health condition succeeds, and FleeToCover runs. Chase is not ticked this frame. The priority comes from the order of the branches, not from editing every state.
The comparison in one table
| Finite state machine | Behavior tree | |
|---|---|---|
| Unit of logic | One state, such as Chase | One branch or sub-tree, such as FleeToCover |
| Reuse | Copy the behaviour into each state that needs it | Attach the same sub-tree wherever it is needed |
| Priority | Encoded in every transition out of a state | Encoded by branch order in a Selector |
| Best fit | A few clear modes, such as idle, patrol, chase | Many behaviours that combine and interrupt each other |
So for a simple enemy with three or four modes, an FSM is often the clearer choice. When the NPC needs the same behaviours combined in different ways, the behavior tree wins because those behaviours are built once and reused.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-67How would you test navmesh pathfinding for a level, and how do you handle dynamic obstacles that force agents to replan without blowing the frame budget?
The 90-second answer
I test the navmesh in two layers. First, deterministic headless tests that run the same A* over the same baked mesh and compare the result to a known-good path. Second, live simulation tests where I spawn agents, drop obstacles, and measure whether they reach the goal, how long replanning takes, and whether the frame budget survives.
For dynamic obstacles I separate three cases, because they need different responses. A moving agent you can steer around is avoidance. A temporary blocker, like a closed door or a fallen crate, is a cost or carve update plus a local replan. A permanent change, like a destroyed wall, is a rebake or tile update. Replanning every agent every frame is what blows the budget, so I stagger it, cache it, and only replan agents whose current path actually intersects the change.
How the path itself works, and what I assert
A navmesh is a set of convex polygons. A* runs over polygon adjacency, not grid cells, so the raw result is a corridor of polygons. A funnel pass then string-pulls that corridor into a short polyline of waypoints. If I only test the corridor, I miss the bugs that matter in game: a path that is topologically valid but cuts a corner through a wall, or a funnel that produces a waypoint inside a door frame.
My golden tests therefore assert three things on the final smoothed path, not just the A* node list:
- Every segment stays inside the mesh and clear of static geometry. I sample each segment at 0.25 m intervals and point-test against the mesh and a capsule sweep against colliders.
- Path length is within a tolerance of the expected length for that level layout. I label the figure as a test fixture, for example corridor A to B is 42.0 m, and fail if the result is more than 5% longer, which catches a heuristic or cost bug that still finds a route.
- The path is stable. Running the same query 100 times returns the identical waypoint list. Non-determinism usually means an uninitialised cost, a tie-break that depends on hash order, or a race in a parallel bake.
// Headless test, run in CI without rendering. C++17, Recast/Detour style API.
TEST(NavMesh, CorridorPathStaysInsideMesh) {
NavMesh mesh = LoadBakedMesh("level1.navmesh");
Path path = mesh.FindPath({0,0,0}, {40,0,0}, agentRadius);
ASSERT_TRUE(path.complete);
EXPECT_LT(path.length, 44.0f); // fixture: optimal is 42.0 m
for (auto seg : path.segments) {
EXPECT_TRUE(mesh.SegmentInside(seg.a, seg.b, agentRadius));
EXPECT_TRUE(CapsuleClear(seg.a, seg.b, agentRadius));
}
EXPECT_EQ(path, mesh.FindPath({0,0,0}, {40,0,0}, agentRadius)); // stable
}I also fuzz the bake. Randomise obstacle placement on a small test level, bake, then run 500 random start and goal pairs. Any pair the level designer marked as connected must return a complete path, and any pair separated by a full wall must return no path. That catches disconnected islands and off-by-one polygon adjacency far better than hand-picked cases.
Dynamic obstacles: carve, cost, avoid
| Obstacle type | Example | Response | Replan trigger |
|---|---|---|---|
| Agent or vehicle | Enemy, cart | Local avoidance steering, no mesh change | Only if avoidance fails for 0.5 s |
| Temporary blocker | Closed door, crate | Carve the affected tiles or add a high cost polygon | Path intersects the carved area |
| Permanent change | Destroyed wall, new building | Rebake affected tiles, update adjacency | Path uses a removed polygon |
| Cost change | Fire, deep water | Raise traversal cost, keep mesh | New cost makes another route cheaper |
Carving is the trap. Removing polygons for a moving obstacle every frame forces tile updates and invalidates paths that were fine. I carve only for obstacles that stay put for at least a second, and I batch carve updates once per physics tick, not per obstacle. For a door that opens and closes, I prefer a cost modifier or an off-mesh link with a traversal check, so the mesh stays intact and the pathfinder can decide at traversal time whether the door is passable.
Replanning without blowing the budget
Say I have 120 agents and a 2 ms AI budget per frame at 60 fps. A full A* over a 20,000 polygon mesh might cost 0.3 to 1.0 ms in my test level, so replanning all 120 in one frame is impossible. I use three controls.
First, dirty checking. When an obstacle changes, I test each agent's remaining path against the changed bounds. In a typical drop, 5 of 120 paths intersect, so only 5 replan. The trace looks like this: crate lands at frame 100, bounds check marks agents 12, 47, 51, 88 and 103 dirty, the replan queue processes 2 per frame, and the rest keep following their old path until their turn. Agents whose path is blocked outright stop and wait rather than walking into the crate.
Second, staggered and prioritised queue. Nearest to the obstacle and closest to their next waypoint go first. I cap replans per frame, for example 4, and spread the rest over subsequent frames. If the queue grows beyond, say, 32, I switch to a cheaper fallback: keep the old corridor, steer to the nearest valid polygon, and replan from there.
Third, path caching and partial replans. If only the tail of a path is blocked, I replan from the agent's current polygon to the goal and reuse the valid head. If the goal moved slightly, I check whether the existing path still ends within the goal radius before replanning at all.
Failure modes I test for explicitly
Agents oscillating between two routes when costs are nearly equal. I add a small hysteresis, so an agent does not switch routes unless the new route is at least 10% shorter. Agents bunching at a doorway after a replan, because every agent picks the same new corridor. I add a per-corridor congestion cost that rises with the number of agents already routed through it. And the classic one: an agent replans onto a path that leads through a polygon that was carved a frame later, so it walks into the obstacle. I version the mesh, stamp each path with the version it was computed against, and revalidate the next waypoint against the current version before stepping onto it.
The live test that ties it together drops a crate into a busy corridor with 60 agents running, records frame time, replan count and arrival rate, and fails if p95 frame time exceeds the AI budget or if fewer than 95% of agents arrive within 30 seconds. That is the number I can defend in a review, not a claim that replanning is fast in general.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-68How would you test seeded procedural dungeon generation so the same seed always produces the identical dungeon, and what breaks reproducibility across platforms and builds?
The 90-second answer
I would treat the seed as an input to a pure function and test that function, not the rendered level. Generate(seed, version) -> DungeonData should return the same tile grid, room list, spawn points and loot in the same order on every run, on every machine, in debug and release. The test harness runs a fixed set of golden seeds, hashes the canonical dungeon data, and compares it to a checked-in hash. A second suite fuzzes thousands of random seeds and checks invariants that must hold for any seed: connectivity, bounds, no overlaps. If either suite fails, generation changed.
The hash is the core check because eyeballing a dungeon misses a moved door or a swapped loot table. Canonical means I sort or iterate in a fixed order before hashing. Rooms sorted by (y, x), tiles scanned row by row, loot sorted by tile index. Hashing the live object graph in scene order would make the test depend on load order.
// C++17. Own RNG: std::uniform_int_distribution and std::rand are not
// guaranteed to produce the same sequence across standard libraries.
struct Rng {
uint64_t s;
explicit Rng(uint64_t seed) : s(seed) {}
uint64_t next() {
uint64_t z = (s += 0x9e3779b97f4a7c15ULL);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
return z ^ (z >> 31);
}
uint32_t range(uint32_t lo, uint32_t hi) { // [lo, hi)
return lo + static_cast<uint32_t>(next() % (hi - lo));
}
Rng fork(uint64_t tag) const { // independent stream per subsystem
Rng r(s ^ (tag * 0x9e3779b97f4a7c15ULL));
r.next();
return r;
}
};
uint64_t HashDungeon(const DungeonData& d) {
uint64_t h = 14695981039346656037ULL; // FNV-1a 64-bit offset basis
auto mix = [&](uint64_t v) {
for (int i = 0; i < 8; ++i) {
h ^= (v >> (8 * i)) & 0xff;
h *= 1099511628211ULL; // FNV prime
}
};
mix(d.width); mix(d.height);
for (uint8_t tile : d.tiles) mix(tile); // row-major, fixed order
for (const Room& r : d.rooms) { mix(r.x); mix(r.y); mix(r.w); mix(r.h); }
for (const Spawn& s : d.spawns) { mix(s.tileIndex); mix(s.kind); }
return h;
}Forked streams versus one shared stream
With one shared Rng passed through every stage, generation is deterministic as long as the call order never changes. That is simpler, and for a small linear pipeline, rooms then corridors then loot with no branching, I would keep it. There is no tag table to maintain and no risk of two forks colliding.
The cost appears when I add a stage. Inserting a new loot table between corridors and spawns shifts every later draw, so all golden hashes change even though rooms and corridors are untouched. Forking fixes that: Rng(seed).fork(1) for rooms, fork(2) for corridors, fork(3) for loot. Adding loot then does not shift the room sequence, and a regression localises to one subsystem hash. The trade-off is real complexity. Tags become part of the saved format, a fork added late can accidentally reuse a tag, and debugging a single stream by logging draws is harder across four streams. I pay that cost only when stages evolve independently or run in parallel. For a frozen generator with three stages, the single stream wins on simplicity.
Golden and fuzz tests
| Seed | Rooms | Tiles | Hash (hex) | Expected |
|---|---|---|---|---|
| 1 | 12 | 64x64 | 8f3a1c04d2e5b771 | match |
| 12345 | 14 | 64x64 | a91f77c0b3d204e8 | match |
| 987654321 | 9 | 64x64 | 04c2e8a1f5b693d0 | match |
| 12345, release ARM | 14 | 64x64 | a91f77c0b3d204e8 | match |
Those hashes are illustrative. In the repo the golden file is generated once, reviewed in a pull request, and then frozen. A test that regenerates its own expected value on every run proves nothing.
The fuzz suite runs, say, 10,000 seeds in CI overnight. At roughly 20 ms per dungeon that is 200 seconds single-threaded, so I shard it across 8 workers for about 25 seconds. For each seed it asserts: every room tile is reachable from the spawn by flood fill, no two rooms overlap, the exit exists, and the hash equals a second generation in the same process. The second generation catches state leaking between calls, such as a static counter or a reused RNG member.
What breaks reproducibility
The usual culprits are nondeterministic iteration and platform-dependent math. unordered_map iteration order depends on hash values and insertion history, so placing loot by iterating a map of tile types gives a different dungeon after a rehash. Parallel room placement with a shared RNG makes the result depend on thread scheduling. Floating point room sizes or jitter computed with sin can differ between x86 and ARM, so I keep layout in integers and quantize any float input before it reaches the RNG. Using wall-clock time, a GUID, or a pointer address as a seed source also sneaks in, usually through a debug helper left in a generator.
I also version the generator. Generate(seed, 3) with a bumped version when I change room placement rules. Old daily seeds and saved runs then still reproduce, and a hash mismatch after a version bump is expected rather than a silent change to live content. When a mismatch does appear unexpectedly, I bisect by subsystem hash: hash rooms alone, corridors alone, loot alone. The first subsystem whose hash diverges points at the change, which is faster than diffing two 64x64 grids by eye.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-69How would you implement a 5% loot drop with a uniform random threshold and test that the observed rate over a million trials matches 5% within tolerance?
The 90-second answer
Draw one uniform value in [0, 1) per roll and compare it to the drop probability. r < 0.05 gives a 5% drop because exactly 5% of the interval [0, 1) lies below 0.05. Then do not eyeball the result. Run a fixed number of trials with a fixed seed, count successes, and compare the count to the binomial distribution for that p and n. If the count sits more than about three standard deviations from the mean, the implementation or the RNG stream is suspect.
// C++17, checked against std::mt19937_64 and std::uniform_real_distribution
#include <random>
#include <cstdint>
struct LootRoller {
std::mt19937_64 rng;
std::uniform_real_distribution<double> dist{0.0, 1.0};
explicit LootRoller(std::uint64_t seed) : rng(seed) {}
bool Roll(double dropChance) { // dropChance in [0, 1]
return dist(rng) < dropChance; // [0,1) so 0 never drops, 1 always drops
}
};Two details decide correctness here. First, the interval must be half open. uniform_real_distribution is specified as [a, b), so r < p is exact. Writing r <= p adds the single endpoint value and, with a discrete generator, slightly inflates the rate. Writing rand() % 100 < 5 is worse: modulo bias makes low residues more likely when the range of rand() is not a multiple of 100, and the granularity is 1% steps, so 5.5% is impossible.
Second, the RNG must not be reseeded per roll. Seeding from the clock or from frame count inside Roll collapses the stream: rolls in the same millisecond return the same value, so a player who kills ten enemies in one frame either drops ten times or zero times. Seed once at startup, or once per test run, and keep drawing from that stream.
Verifying the rate
For n independent rolls with probability p, the success count X follows Binomial(n, p). The mean is np and the variance is np(1-p), so the standard deviation is sqrt(np(1-p)). That gives a concrete pass band instead of a vague "close to 5%".
Worked example, hypothetical but computed exactly: p = 0.05, n = 1,000,000.
- Expected drops: 1,000,000 x 0.05 = 50,000
- Standard deviation: sqrt(1,000,000 x 0.05 x 0.95) = sqrt(47,500) = 217.9
- Three sigma band: 50,000 +/- 654, so 49,346 to 50,654
- As a rate: 4.935% to 5.065%
A run that lands at 49,800 passes. A run at 48,900 fails at roughly five sigma, which happens by chance about once in 1.7 million runs, so treat it as a bug, not bad luck. The same arithmetic scales the test cost:
| Trials n | Expected at 5% | SD | 3-sigma rate band |
|---|---|---|---|
| 10,000 | 500 | 21.8 | 4.35% to 5.65% |
| 100,000 | 5,000 | 68.9 | 4.79% to 5.21% |
| 1,000,000 | 50,000 | 217.9 | 4.93% to 5.07% |
Ten thousand trials cannot distinguish 5.0% from 5.5%. If design cares about that difference, the test needs the larger n. A million rolls of a trivial function takes well under a second in a native test, so there is no reason to accept the wide band.
Test shape
// Deterministic test: same seed, same result, every run
int successes = 0;
LootRoller roller(12345);
const int n = 1'000'000;
for (int i = 0; i < n; ++i) if (roller.Roll(0.05)) ++successes;
// Pass if successes in [49346, 50654]Fixing the seed makes the test reproducible in CI. A failure then points at a code change, not at a random Tuesday. Keep one separate smoke run with a random seed if you want to catch a generator that only behaves for one seed, but do not gate the build on it.
Also test the edges directly, because the aggregate test will not catch them quickly. Roll(0.0) must never drop over 100,000 rolls, Roll(1.0) must always drop, and a negative or above-one chance should be clamped or rejected at the data layer, since r < 1.5 silently drops everything. For tiered loot, extend the same idea with cumulative thresholds: draw one r, walk the cumulative weights, and verify each tier count against its own binomial band, plus a chi-square check across tiers to catch a tier that is starved while the total rate still looks right.
The failure mode I see most often is not the threshold. It is the pity timer or the guaranteed-drop counter layered on top, which changes the effective rate by design. If a pity rule exists, test the base roll in isolation first, then test the combined system against the rate design actually intends, and document that the combined rate is no longer 5%.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-70In what order do you draw transparent objects, and why does that order matter for alpha blending?
The 90-second answer
Draw transparent objects back to front, farthest from the camera first, after all opaque objects. Turn depth writes off for them while keeping the depth test on.
That order matters because alpha blending mixes a new colour with whatever is already in the framebuffer. The standard blend for a source colour over a destination is:
C_out = C_src * A_src + C_dst * (1 - A_src)C_dst is the accumulated result of everything drawn before. Draw a near pane first and a far pane later, and the far pane blends over the near one. The image looks as if the far surface is in front.
Worked trace
Opaque background is blue (0, 0, 1). A red pane with alpha 0.5 is behind a yellow pane with alpha 0.5.
Correct order, red first:
Red over blue: 0.5 * (1,0,0) + 0.5 * (0,0,1) = (0.50, 0.00, 0.50)
Yellow over that: 0.5 * (1,1,0) + 0.5 * (0.50,0,0.50) = (0.75, 0.50, 0.25)Reversed order, yellow first:
Yellow over blue: 0.5 * (1,1,0) + 0.5 * (0,0,1) = (0.50, 0.50, 0.50)
Red over that: 0.5 * (1,0,0) + 0.5 * (0.50,0.50,0.50) = (0.75, 0.25, 0.25)Green differs, 0.50 against 0.25. The reversed draw shows too little yellow and too much red, as if the panes swapped places.
Sorting
Sort the transparent list each frame by distance from the camera, using squared distance to avoid a square root per comparison:
std::sort(transparent.begin(), transparent.end(),
[](const RenderItem& a, const RenderItem& b) {
return a.distSq > b.distSq; // farthest first
});Depth writes stay off because a semi-transparent pixel does not fully hide what is behind it. Writing depth would block later transparent pixels that should still show through. The depth test stays on so opaque geometry already drawn still occludes transparent pixels behind it.
The sort uses object centres, so large or intersecting transparent meshes can still order incorrectly where they overlap on screen. Splitting those meshes is the usual fix.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-71Two coplanar surfaces flicker at distance but look fine up close. How do you diagnose depth buffer precision versus separation, and when does polygon offset actually fix it?
The 90-second answer
Z-fighting is two fragments competing for the same depth value, so the winner flips per pixel and per frame as the camera moves. It gets worse with distance because a perspective depth buffer does not distribute precision evenly. Most of the 24-bit depth range is spent near the camera. Two surfaces separated by 1 cm can be resolvable at 5 m and indistinguishable at 200 m.
I would first check whether the surfaces are truly coplanar, then tighten the depth range, then separate them in depth. Polygon offset is the last step, not the first. It biases the depth test for the decal or overlay, which helps when the separation is small but consistent. It does not create precision that the buffer lacks.
Why distance kills precision
For a perspective projection, depth in the buffer is roughly proportional to 1/z, not z. A useful approximation for the smallest resolvable separation at distance z is:
delta_z ≈ z^2 / (near * 2^24) for a 24-bit depth buffer
Take a typical setup, near = 0.3 m, far = 2000 m. That far plane is common in open levels and it is expensive.
| Camera distance | Approx. resolvable separation |
|---|---|
| 10 m | 0.02 mm |
| 50 m | 0.5 mm |
| 100 m | 2 mm |
| 500 m | 50 mm |
A road decal laid 5 mm above terrain will look stable up close and flicker past roughly 150 m. A wall panel offset by 20 mm from a wall will survive much farther. This is why the bug often appears only in the wide shot, or only when the player looks down a long corridor.
The near plane dominates the calculation. Moving near from 0.1 m to 0.5 m improves precision fivefold at every distance, at the cost of clipping geometry the camera gets close to. Moving far from 2000 m to 500 m helps less than people expect once near is very small, because the ratio matters more than either value alone. A ratio of 10,000:1, such as near 0.1 and far 1000, is where coplanar detail starts to break down in practice.
In RenderDoc I would capture the frame, inspect the depth prepass or the depth buffer view, and step the camera forward in 1 m increments. If the flicker starts at a repeatable distance and the two surfaces have almost identical depth values there, precision is the cause. If they flicker even at 2 m, the surfaces are probably exactly coplanar or the offset is being applied inconsistently between passes.
Polygon offset, and its limits
Polygon offset shifts the depth value used for the test by an amount that depends on the polygon slope. In OpenGL:
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(-1.0f, -1.0f); // factor, units
DrawDecal();
glDisable(GL_POLYGON_OFFSET_FILL);The factor scales with the slope of the polygon in window space. The units term is a fixed shift in depth buffer steps. Negative values pull the decal toward the camera in depth, so it wins the test against the surface underneath. In Direct3D the equivalent is a depth bias on the rasterizer state, and in Unity it is exposed through material settings or a custom shader. The principle is the same.
Offset works well for a decal on a flat floor, a road marking, or a panel on a wall, where the two surfaces are nearly parallel and the required shift is small. It fails in three predictable ways. At a glancing angle the slope term grows, so the same settings that fix the floor at noon can push a decal through a nearby curb at a shallow angle. A large offset can make the decal win against geometry that should occlude it, such as a crate sitting on the road. And offset cannot help if the depth values are already identical after rounding, because the bias is applied in the same quantized space.
What I would ship instead of relying on offset alone
For a new project I would set near as large as gameplay allows, often 0.3 to 0.5 m for a third person game, and split the far plane or use a logarithmic depth buffer for large worlds. Reverse Z is the other standard fix, but only with a 32-bit float depth buffer. Reverse Z maps near to 1 and far to 0, so with a float format the dense precision near 0 lands at far distances and precision becomes much more uniform across the range. With a 24-bit integer depth buffer, reverse Z gives little or no gain, because integer steps are uniform and the projection still clusters values. It also requires care with early Z and with any shader that reads depth directly.
For the specific surfaces, I would give them real separation in world space where possible. A decal 2 cm above the floor, a road mesh 5 cm above terrain, and a wall panel 3 cm off the wall will survive at distances where 5 mm will not. Where separation is impossible, such as a decal that must hug a curved surface, I would use a stencil based decal or a projected decal that writes depth itself, rather than fighting the depth test.
The test I would run before calling it fixed: place the camera at the worst angle and the worst distance in the level, move it slowly across the surface, and capture with RenderDoc at the point where it used to flicker. If the depth values for the two surfaces differ by more than a few buffer steps across the whole surface, the fix will hold. If they differ by one step or less, the next camera position will bring the flicker back.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-72How does normal mapping fake surface detail without extra geometry, and how do you compute the perturbed normal in the fragment shader?
The 90-second answer
Normal mapping stores a fake surface normal per texel instead of adding triangles. The geometry stays flat, the lighting pretends it is bumpy. A normal map is authored in tangent space, so its RGB channels do not mean world X, Y, Z. They mean the surface's own frame: R is the tangent direction, G is the bitangent direction, B is the direction out of the surface. At a pixel you decode that vector, rotate it into world space with the interpolated tangent frame, then use the result for lighting.
The frame comes from the mesh. Each vertex carries a tangent, usually generated offline with MikkTSpace so UV seams and mirrored islands get consistent frames. The vertex shader passes world normal N and tangent T to the fragment shader. Interpolation makes T and N drift out of alignment, so the fragment shader rebuilds an orthonormal frame before it samples anything.
// HLSL, per-pixel, tangent-space normal map
float3 nTex = normalMap.Sample(sampler, uv).rgb * 2.0 - 1.0; // [-1,1]
float3 N = normalize(vWorldNormal);
float3 T = normalize(vWorldTangent - N * dot(N, vWorldTangent)); // Gram-Schmidt
float3 B = normalize(cross(N, T)) * vTangentSign; // sign fixes mirrored UVs
float3 perturbed = normalize(T * nTex.x + B * nTex.y + N * nTex.z);
float ndl = saturate(dot(perturbed, normalize(lightDir)));
float3 colour = albedo * (ambient + lightColour * ndl);Worked trace. A flat texel reads (128, 128, 255). Decoded, that is about (0, 0, 1), the surface normal itself, so perturbed equals N and lighting matches the flat mesh. A texel on a scratch reads (200, 128, 200). Decoded, that is (0.57, 0, 0.57). Before normalisation it points 45 degrees between T and N, and normalising keeps that angle. With a light aligned to N, ndl drops from 1.0 to cos(45 degrees), about 0.71, so the scratch darkens even though the silhouette and the triangle count never changed. That is the whole trick: per-pixel orientation changes, per-vertex geometry does not.
| Technique | Extra geometry | Silhouette changes | Cost per pixel |
|---|---|---|---|
| Flat shading | None | No | One normal fetch, no decode |
| Normal mapping | None | No | One fetch, decode, frame transform |
| Displacement mapping | Tessellated mesh, often 10x to 100x vertices | Yes | Vertex displacement plus a normal fetch |
Where it breaks in practice
Seams show up first. Two UV islands that share an edge in 3D space sample unrelated texels, and if their tangent frames disagree the lighting splits along the seam. The fix is usually in the asset pipeline: weld UVs, generate tangents with the same algorithm the engine expects, and check the mesh in a debug view that colours tangent, bitangent and normal. A second classic bug is the green channel convention. OpenGL style maps store Y up, DirectX style maps store Y down. Importing one as the other inverts the tilt, so bumps look like dents under a moving light. The vTangentSign term above handles the related case of mirrored UVs, where the bitangent flips and the frame becomes left-handed.
Resolution is the other limit. A 512x512 normal map stretched over a 4 metre wall gives roughly 8 mm per texel, so fine scratches alias and shimmer as the camera moves. Mipmaps help by averaging normals, but averaging also shrinks the vector, which is why distant normal mapped surfaces look washed out. Engines counter that with normal map mip bias, anisotropic filtering at 8x or 16x for grazing angles, and sometimes derivative based normal mapping, which recomputes the frame from screen space derivatives of world position and UV. Derivatives survive seams better and need no stored tangents, at the cost of extra ALU and some instability on flat, low frequency areas.
Compression matters too. A normal map stored as BC7 or BC5 keeps the XY pair that actually carries the tilt. Storing it as a plain colour texture wastes bits on the B channel, which sits near 1.0 almost everywhere. When you see a normal mapped surface that looks correct up close and turns to plastic at distance, check the mip chain and the compression before you blame the shader. The geometry was never the problem. The per-pixel frame was.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-73Walk me through how you would test Lambert and Phong lighting terms in a shader, and what changes when you move diffuse and specular response to PBR?
The 90-second answer
Lambert and Phong are the two terms I would write first in a test shader, then replace with a PBR model once the test scene exposes their failures. Lambert gives diffuse response from the angle between surface normal and light direction. Phong adds a specular highlight from the reflection of that light about the normal. Both are cheap and predictable, which makes them good for unit tests. Neither conserves energy, neither has a physical Fresnel term, and Phong's highlight shape depends on an arbitrary shininess exponent. PBR, usually Cook-Torrance with GGX, fixes those three problems with parameters artists can reuse across materials: albedo, roughness, metalness, and F0.
Lambert and Phong, with numbers
Assume a unit normal N, a unit direction to the light L, and a unit direction to the camera V. All three are in world or view space, consistently.
// HLSL, checked against SM6 conventions
float3 N = normalize(normalW);
float3 L = normalize(lightDirW);
float3 V = normalize(cameraPosW - posW);
float ndl = max(dot(N, L), 0.0);
float3 diffuse = albedo * ndl; // Lambert, albedo already includes kd
float3 R = reflect(-L, N);
float rdv = max(dot(R, V), 0.0);
float3 specular = specColor * pow(rdv, shininess); // Phong
float3 color = lightColor * (diffuse + specular) * attenuation;Worked trace, labelled as a hypothetical test case. Let N = (0,1,0), L = normalize(0.707, 0.707, 0), so the light is 45 degrees from the normal. Then ndl = 0.707. With albedo 0.8 grey, Lambert diffuse is 0.566 before light colour and attenuation. R = reflect(-L, N) = (0.707, 0.707, 0). If the camera sits along R, rdv = 1 and Phong specular is specColor regardless of shininess. Move the camera 30 degrees away from R and rdv = cos(30°) = 0.866. With shininess 32, specular falls to 0.866^32 = 0.010. With shininess 8 it is 0.866^8 = 0.316. That sensitivity is the testable behaviour: same geometry, same light, highlight width controlled only by the exponent.
Blinn-Phong replaces R with the half vector H = normalize(L + V) and uses pow(max(dot(N,H),0), shininess). It is cheaper on some hardware and often looks tighter, but it is still an empirical exponent with no link to microfacet roughness.
How I test the terms before PBR
I build a small scene with a sphere and a flat quad, one directional light, no shadows, no tone mapping, and render to a float target. I set known normals by using the quad, then read back pixels and compare against the formulas above within a tolerance for float rounding, typically 1e-3 for a unit test.
| Test case | Lambert expectation | Phong expectation | What it catches |
|---|---|---|---|
Light behind surface, ndl < 0 | 0 | 0 | Missing clamp, light leaking through back faces |
| Light at 45°, camera on reflection vector | 0.707 * albedo | Full specColor | Wrong space for L, V or R |
| Camera 30° off reflection, shininess 32 vs 8 | Unchanged | 0.010 vs 0.316 of peak | Exponent applied to wrong dot product |
Grazing light, ndl near 0 | Near 0 diffuse | Highlight can still appear | Specular without diffuse, a Phong artefact |
That last row is the bridge to PBR. Phong can produce a bright highlight on a surface receiving almost no diffuse light, and diffuse plus specular can exceed the incoming light energy. In a game that shows up as chalky metals and highlights that do not dim when a surface turns away from the light.
The move to PBR
PBR splits outgoing light into diffuse and specular parts that share energy:
float3 F0 = mix(float3(0.04), albedo, metalness); // dielectric base reflectance
float3 F = fresnelSchlick(max(dot(N, V), 0.0), F0);
float3 kS = F;
float3 kD = (1.0 - kS) * (1.0 - metalness);
float3 diffuse = kD * albedo / PI;
float3 specular = D_GGX(N, H, roughness) * G_SchlickGGX(N, V, roughness)
* G_SchlickGGX(N, L, roughness) * F
/ (4.0 * max(dot(N, V), 0.001) * max(dot(N, L), 0.001));
float3 Lo = (diffuse + specular) * lightColor * ndl * attenuation;Three changes matter in practice. First, Fresnel: reflectance rises at grazing angles for every material, so a dielectric at F0 = 0.04 still reflects strongly when viewed edge on. Phong has no such term, so edges look dull unless an artist fakes it. Second, GGX distribution: roughness maps directly to the spread of microfacets, replacing shininess with a parameter that also drives the geometry term G. Third, energy sharing: kD shrinks as kS grows, and metals set metalness = 1, which zeroes diffuse and tints specular with albedo. That is why a copper PBR material looks coloured in its highlight while a Phong copper with white specular and brown diffuse looks painted on.
Failure modes I check in the PBR version
Roughness at 0 with a GGX denominator near zero produces fireflies, so I clamp ndl and ndv denominators and test a roughness sweep from 0 to 1 on the same sphere. Metalness between 0 and 1 on a single surface, rather than per material, gives muddy results, so I test pure dielectric and pure metal endpoints first. Normal maps that are not normalised after interpolation break ndl and ndv, which shows up as dark bands at grazing angles in the test scene. Finally, I compare the PBR sphere against the Lambert and Phong renders at matched light intensity. If the PBR version is darker overall, the usual cause is a missing 1/PI in one model and not the other, a mismatch I can spot from the numeric trace rather than by eye.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-74In shadow mapping, what does increasing normal bias do to shadow acne on sloped surfaces?
The 90-second answer
Normal bias offsets the position used to sample the shadow map along the surface normal. Increasing it moves the sample point off the surface, so a sloped surface is less likely to compare itself as occluded. That reduces shadow acne on slopes. Push it too far and the shadow detaches from the caster, which artists call peter-panning.
Constant bias, by contrast, adds a fixed amount to the depth comparison. It does not account for how stretched a shadow texel becomes on a grazing surface, so it is a poor primary fix for slopes.
Why slopes need normal bias
A shadow map texel covers a small area when the surface faces the light. On a slope, the same texel covers a much longer strip of surface. Depth varies across that strip, but the shadow map stores one depth for the texel. Parts of the strip can therefore test as deeper than the stored depth and incorrectly fail the shadow test. That failure is acne, usually seen as parallel stripes.
Normal bias helps because the offset follows the surface orientation. The sample point moves away from the surface in the direction it faces, which compensates for the stretched footprint. A fixed depth offset cannot do that as directly.
Worked example
Assume a 2048 x 2048 shadow map covers 40 m, so one texel is about 0.02 m across. On a surface tilted 75 degrees from the light, the footprint stretches to roughly 0.02 / cos(75 degrees), or about 0.077 m. A normal bias near 0.02 m, one texel in world units, is a sensible starting value. If acne remains on that slope, raise it in small steps, for example 0.02 m, 0.03 m, 0.04 m, and watch the contact shadow under a nearby box.
// World position and normal for the shaded fragment
float3 samplePos = worldPos + normal * normalBias;
float shadow = shadowMap.SampleCmpLevelZero(sampler, samplePos);In a real engine the projection of samplePos into shadow map space happens before the comparison, and normalBias is often set per light or per shadow cascade based on texel size.
| Setting | Effect on acne | Effect on contact |
|---|---|---|
| Normal bias too low | Stripes remain on slopes | Shadow stays tight to the caster |
| Normal bias in range | Stripes disappear | Contact shadow still touches the caster |
| Normal bias too high | No acne | Shadow slides off edges, thin objects lose grounding |
How to check it quickly
Use a test scene with flat and sloped planes under one directional light and a box casting onto both. Freeze the shadow camera so texels do not swim. Raise normal bias until the sloped plane is clean, then check the box. If a bright gap opens between the box and the plane, you have gone too far. Back off slightly and, if needed, tighten the shadow camera frustum to improve texel density instead of raising bias further.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-75Your explosion needs 20,000 particles at 60 fps on CPU and GPU paths, how do you test which fits the frame budget and pool spawns so cost stays bounded when the pool runs dry?
The 90-second answer
I would not pick CPU or GPU from particle count alone. I would measure three separate costs on the target hardware: simulation update, spawn and death, and rendering including overdraw. Then I would put a hard cap on live particles and a hard cap on spawns per frame, because an uncapped emitter is what turns a visual effect into a frame spike.
For a 20,000 particle explosion at 60 fps, the frame budget is 16.6 ms total. If particles get 2 ms for simulation, that is 100 ns per particle per frame on CPU. A simple CPU particle with position, velocity, life and colour in a struct of arrays can update in roughly 20 to 40 ns when the data fits in cache and there is no branching per particle. At 20,000 particles that is 0.4 to 0.8 ms. That sounds fine until spawn happens. Initialising 20,000 particles with random spread, allocation, or a virtual call per particle can cost several milliseconds in one frame, even if steady state update is cheap.
GPU simulation removes that CPU update cost. Particles live in a GPU buffer, a compute shader or transform feedback updates them, and the CPU only sends emitter parameters. The catch is that the buffer size is fixed at creation. You cannot grow it mid burst without a reallocation and a pipeline stall, and you cannot easily read particle state back on CPU for collision or gameplay. Sorting for transparency also becomes expensive or approximate.
So my test is: run the same emitter on both paths, with the same cap, and record CPU time, GPU time, and frame p99 over a burst, not just an average.
Worked numbers
Assume a CPU particle is 32 bytes: position 12, velocity 12, life and size 8. At 20,000 live particles that is 640 KB. That exceeds L2 on many consoles and will stream from memory every frame. Update cost is therefore memory bandwidth, not arithmetic. 640 KB read plus 640 KB write at 60 fps is about 77 MB/s, which is fine, but cache misses per particle dominate if the layout is array of structs with padding or if each particle carries a pointer to a material.
Spawn cost is the spike. If spawn does new Particle() or pushes into a std::vector that reallocates, one burst can allocate 640 KB and fragment the heap. With a pool, spawn is: pop an index from a free list, write the fields, increment the live count. That is a few stores per particle, no allocation, no lock if the emitter is single threaded.
On GPU, 20,000 particles as instanced quads is 80,000 vertices before overdraw. If each particle covers 200 pixels on screen, that is 16 million shaded pixels for one explosion. Fill rate, not vertex count, becomes the limit. I would test with the camera pushed into the explosion, because that is where GPU particle systems fail in production while looking fine in a wide shot.
| Cost | CPU pooled | GPU simulated |
|---|---|---|
| Steady update | 0.4 to 0.8 ms at 20k, scales linearly | Near zero CPU, GPU time depends on buffer size |
| Spawn burst | Bounded if pooled, unbounded if allocating | Bounded, buffer preallocated, excess dropped or recycled |
| CPU readback for gameplay | Free, data is on CPU | Expensive, stalls pipeline if you read back |
| Sorting and transparency | CPU sort is O(n log n) and costly at 20k | Hard, usually unsorted or sorted in compute |
| Failure mode | Cache misses, spawn spike | Overdraw, fixed cap, no per particle CPU logic |
Pooling and bounding spawn
I preallocate the maximum live count at load time, not at first burst. The pool is a flat array plus a free list. Live particles are kept compact so iteration touches only live entries. Death swaps the last live particle into the dead slot.
struct Particle { float px, py, pz, vx, vy, vz, life, size; };
struct Pool {
std::vector<Particle> data; // size = maxLive, allocated once
std::vector<int> freeList; // indices, reserved to maxLive
int live = 0;
bool spawn(const Particle& p, int budget) {
if (budget <= 0 || freeList.empty()) return false;
int idx = freeList.back(); freeList.pop_back();
data[idx] = p;
++live;
return true;
}
void kill(int i) { // swap with last live slot in a compact array
data[i] = data[live - 1];
--live;
}
};The emitter also gets a per frame spawn budget, for example 2,000 spawns per frame. If the effect requests 20,000 in one frame, it spawns 2,000 per frame for 10 frames, or it scales the emission rate down. That spreads cost and avoids a single frame taking the whole budget.
When the pool runs dry I need a policy decided before shipping, not a crash. Options are drop new particles, recycle the oldest live particle, or reduce particle size and count for the rest of the burst. For an explosion I recycle oldest, because a missing tail looks worse than a slightly shorter lived early particle. For a continuous emitter like a torch I drop new spawns, because recycling would make the flame flicker. The policy is per emitter, and the pool reports exhaustion as a counter so I can see it in a debug overlay.
How I test it
I add CPU markers around spawn, update, kill and render submission, and GPU markers around the particle draw. I run three scenes: steady emission at cap, a single burst from empty, and repeated bursts with the pool already full. I record p50 and p99 frame time on the lowest spec target, with the camera in the worst case position for overdraw. If p99 crosses the particle budget, I cut maxLive, cut particle screen size, or move simulation to GPU. I never accept a result from a development PC with a discrete GPU as proof for a handheld or integrated GPU target.
The subtle failure I watch for is the readback stall. A GPU system that looks free on the GPU timeline can stall the CPU every frame if the code checks how many particles are alive by mapping the buffer. That sync cost does not show up as GPU time. It shows up as CPU idle time waiting for the GPU, and it is the reason I keep gameplay relevant particle state on CPU or accept that GPU particles are purely visual.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-76Walk me through how you would blend run and strafe animations with weights over a 0.25 second crossfade, and what breaks if the weights do not sum to one?
The 90-second answer
I treat blending as a weighted sum of sampled poses, with weights that always sum to one, and a crossfade as a timed change of those weights. For a run to strafe change I keep two active clips, sample both at their own times, blend position, rotation and root motion, then write the result to the skeleton. The fade duration, 0.25 s in this example, only controls how fast the weights move. It does not change the blend math.
// C++17, checked against a typical skeletal pipeline
struct ClipWeight { const AnimClip* clip; float weight; float time; };
Pose Blend(const std::vector<ClipWeight>& layers, float dt) {
float sum = 0.0f;
for (auto& l : layers) { l.time += dt * l.clip->rate; sum += l.weight; }
Pose out = Pose::Zero();
for (auto& l : layers) {
float w = l.weight / sum; // normalise every frame
out.AddScaled(l.clip->Sample(l.time), w);
}
return out;
}
struct Crossfade {
ClipWeight from, to;
float duration = 0.25f, elapsed = 0.0f;
void Update(float dt) {
elapsed += dt;
float a = std::clamp(elapsed / duration, 0.0f, 1.0f);
from.weight = 1.0f - a;
to.weight = a;
}
};AddScaled lerps joint positions, slerps quaternions for rotations, and adds root translation scaled by weight. Normalising in Blend is the safety net. The crossfade itself should already produce weights summing to one, but normalising protects against a designer-authored layer list that does not.
Worked trace at 60 fps
Duration 0.25 s is 15 frames. Alpha is elapsed divided by duration.
| Frame | Elapsed | Alpha | Run weight | Strafe weight | Result |
|---|---|---|---|---|---|
| 0 | 0.000 s | 0.00 | 1.00 | 0.00 | pure run |
| 3 | 0.050 s | 0.20 | 0.80 | 0.20 | mostly run |
| 6 | 0.100 s | 0.40 | 0.60 | 0.40 | mid blend |
| 9 | 0.150 s | 0.60 | 0.40 | 0.60 | mostly strafe |
| 15 | 0.250 s | 1.00 | 0.00 | 1.00 | pure strafe, from dropped |
At frame 6 the blended root speed is 0.6 * runSpeed + 0.4 * strafeSpeed. If both clips run at 5 m/s, the character stays at 5 m/s. That is the check I run in a test scene: scrub the fade and confirm the root does not surge or stall at the midpoint.
Where it breaks
Weights that sum to 0.6 shrink the pose toward the bind pose. Arms pull in, the character loses height, and root motion drops to 60 percent. Weights that sum to 1.4 overshoot joint angles and can push feet through the floor. Normalising fixes the scale, but it hides an authoring error, so I assert abs(sum - 1.0f) < 0.001f in debug builds and log the layer names when it fires.
Root motion needs separate handling. If I blend root translation inside the pose and also apply the active clip's root motion in the character controller, the character moves twice during the fade. I blend root motion with the same weights and apply it once, from the blended pose.
Interrupting a fade is the common bug. If the player reverses direction at frame 6, starting a new fade from the original run clip snaps back to pure run. Instead I snapshot the current blended pose as the from state, or keep both clips and retarget the weights from their current values. The new fade then starts at 0.6 and 0.4, not at 1.0 and 0.0.
Loop mismatch causes foot sliding even with correct weights. A run clip that loops every 0.8 s and a strafe clip that loops every 1.1 s will drift out of phase during a long blend. For a 0.25 s crossfade the drift is small, but for a sustained 50/50 blend, such as run plus aim, I match cycle time or use phase synchronisation on the foot contact frames.
Additive blending is a different tool. I use it for an upper body layer, for example aiming, on top of a locomotion base. The base weights still sum to one. The additive layer is added after, scaled by its own weight, and clamped so a 1.0 aim weight does not hyperextend the spine. Mixing the two systems in one weight list is where most pops come from.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-77How would you use two-bone inverse kinematics to keep a character's foot planted while the hips move, and how would you test that it works?
The 90-second answer
I plant the foot target in world space, then solve the leg backwards from that target each frame while the hips move. The thigh and shin lengths are fixed, so the knee position is fully determined by the hip position, the ankle target and a pole vector that says which way the knee should point. If the solve is right, the ankle stays put while the knee bends and straightens to absorb the hip motion. I test that by moving the hips along a path with the target frozen and measuring how far the ankle drifts.
Assumptions: a two-bone leg, a pole vector roughly forward for a humanoid, and a foot target supplied by the animation or a ground probe. IK does not choose the target. It only reaches it.
The solve
Given hip H, ankle target A, thigh length L1, shin length L2 and pole direction P:
// C++17, plain Vector3 math
Vector3 SolveKnee(Vector3 H, Vector3 A, float L1, float L2, Vector3 pole) {
Vector3 toTarget = A - H;
float maxReach = 0.99f * (L1 + L2);
float d = std::min(toTarget.length(), maxReach);
Vector3 dir = toTarget.normalized();
float a = (L1 * L1 - L2 * L2 + d * d) / (2.0f * d);
float h = std::sqrt(std::max(0.0f, L1 * L1 - a * a));
Vector3 bend = (pole - dir * pole.dot(dir)).normalized();
return H + dir * a + bend * h;
}The term a is the distance from the hip along the hip-to-ankle line to the plane the knee sits in. The term h is how far the knee sits off that line. The pole, projected perpendicular to the leg, picks the side. Without it the knee could bend either way and would flip between frames.
The clamp on d matters. If the target is beyond reach, asking for the full L1 + L2 makes h zero and the knee direction unstable. Clamping to 99 percent of reach keeps a small bend and lets the foot slide a little instead of snapping.
Worked trace
Let L1 = L2 = 0.45 m, so reach is 0.90 m. Plant the ankle at A = (0.20, 0.10, 0.00) and put the hip at H = (0.00, 0.90, 0.00).
- Distance
d = sqrt(0.20^2 + 0.80^2) = 0.825 m, inside reach with 7.5 cm spare. a = 0.412 mandh = sqrt(0.45^2 - 0.412^2) = 0.180 m. The knee sits 18 cm off the hip-to-ankle line toward the pole.- Move the hip forward 10 cm to
(0.00, 0.90, 0.10)and keepAfixed. Newd = 0.831 m. The solver recomputesaandh, the knee shifts a few centimetres, and the ankle error stays zero. Hip moved, foot did not. That is the pass condition.
How I test it
I run an automated scene rather than eyeballing one pose. The root follows a straight line at walking speed, then a turn, then a slope. Each frame I log three values.
| Check | Example threshold | Failure it catches |
|---|---|---|
| Foot slide, distance from planted target | under 2 mm in stance | foot skating as the body passes over it |
Reach margin, (L1 + L2) - d | above 1 cm in normal walk | leg snapping straight, then popping back |
| Knee side, sign of bend against pole | never flips | knee bending backwards for a frame on a turn |
I also push the root until the margin crosses zero. Past that point the foot has to slide toward the hip, and the test is that the slide grows gradually. A one-frame jump means the clamp is applied inconsistently.
Foot orientation is separate from position. I align the foot to the ground normal from a downward raycast and slerp toward it. Position IK alone can leave the foot at the wrong angle even with zero ankle error, so I check foot-to-surface distance on the slope case as well.
A cheaper option is a foot raycast with no knee solve, leaving the knee to the animation. That plants the foot but the leg hyperextends or clips when the hips drop. I would only use it for distant crowd characters where the knee is not readable. For a playable character, the two-bone solve above is the one I can defend.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-78How do you stop a fast ragdoll limb from tunneling through a thin floor in a single physics step?
The 90-second answer
Discrete collision only checks where a body ends up. If a limb moves farther in one step than the floor is thick, it can start above the floor and finish below it without ever overlapping, so the solver sees nothing to resolve. Continuous collision detection (CCD) fixes that by testing the path between the previous position and the new position, not just the endpoint.
For a ragdoll I would enable CCD on the fast limbs, usually the hands and feet, and use a swept sphere or capsule cast from the previous centre to the new centre against the floor. The cast returns the earliest time of impact (TOI) along that segment. I then advance the body only to that point, generate the contact there, and let the solver handle the rest of the step from a valid contact instead of a missed one.
Why the numbers force this
Take a fixed step of 1/60 s and a floor collider 0.10 m thick. A limb travelling at 12 m/s moves 0.20 m per step, twice the thickness. At 30 m/s it moves 0.50 m per step. A discrete sphere test at the end position can easily miss a 0.10 m slab at either speed.
| Limb speed | Distance per 1/60 s step | Discrete test against 0.10 m floor |
|---|---|---|
| 3 m/s | 0.05 m | Usually catches it |
| 12 m/s | 0.20 m | Can jump clean over |
| 30 m/s | 0.50 m | Will jump clean over |
Substepping the whole ragdoll to, say, 240 Hz would also reduce the step distance to 0.125 m at 30 m/s, but it multiplies solver cost for every body, including slow ones that do not need it. CCD on the few fast bodies is cheaper and more targeted.
Implementation sketch
// C++-style pseudocode, checked against a typical rigid-body API
Vec3 prev = body.position;
Vec3 next = prev + body.velocity * dt;
if (body.useCCD && body.velocity.length() * dt > body.radius * 0.5f) {
Hit hit = world.sweepSphere(prev, next, body.radius, floorMask);
if (hit.found) {
// Advance to the contact, not past it.
body.position = prev + (next - prev) * hit.toi;
body.velocity = reflectAndDamp(body.velocity, hit.normal,
body.restitution, body.friction);
solver.addContact(body, hit.point, hit.normal, hit.toi);
return; // Skip the normal integrate for this body this step.
}
}
body.position = next;The threshold matters. Running a sweep for every body every step wastes time on bodies moving a few millimetres. I gate it on distance travelled relative to body radius and collider thickness, and I only sweep against layers the limb can actually hit. A ragdoll torso moving slowly does not need the same treatment as a foot whipping at 25 m/s.
How I test it
I drop a ragdoll from a fixed height onto a 0.10 m floor and drive each limb through a speed sweep: 5, 12, 20 and 30 m/s, at several impact angles. The pass condition is mechanical, not visual. After each step I assert that no limb centre is below the floor surface minus its radius plus a small tolerance, say 5 mm, and that a contact was generated on the step where the swept segment first crossed the slab. I also log TOI values. A TOI outside [0, 1], or a contact point behind the previous position, means the sweep setup is wrong even if the ragdoll looks fine on screen.
Two failure modes show up in that test. First, a sweep that reports the hit but still integrates to the full endpoint, which buries the limb and makes the solver pop it back out. Second, CCD enabled on the wrong layer mask, so the sweep hits scenery the ragdoll should pass through, or misses the floor layer entirely. Both are caught by the penetration assertion and by checking which collider produced the hit.
CCD does not make thin geometry free. If the floor were 1 cm thick and the limb moved 0.50 m per step, the sweep still finds the crossing, but the contact is very sensitive to the exact segment and to the sphere radius. In that regime I would thicken the gameplay floor collider, even if the visible mesh stays thin, and keep CCD as the safety net rather than the only line of defence.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-79Walk me through how you would fit 64 players' position, velocity and health updates into 20 KB/s per client at 20 Hz, and how you would test delta compression and update rates before shipping?
The 90-second answer
Start from the budget, not the struct. Say the target is 20 KB/s per client downstream, 20 Hz server tick, 64 players in the world. That is 20,000 / 20 = 1,000 bytes per tick per client, before headers and retransmits. A naive snapshot fails immediately: 64 entities x (position 12 B + velocity 12 B + health 2 B + id 1 B) = 1,728 B per tick, 34.6 KB/s. So I cut three ways, in order: quantize what the client can actually see, send only what changed since that client's last acknowledged baseline, and send distant or irrelevant entities less often.
Quantization first. World is 512 m across. A float position wastes precision the eye cannot use at 100 m. I store position as 16-bit per axis relative to a 16 m cell origin, giving about 0.24 mm resolution inside the cell, and velocity as 8-bit signed per axis scaled to +/-32 m/s. Health is 8-bit 0-100. That drops a full entity to about 9 B packed, still too much at 20 Hz for all 64, which is why delta and interest management do the rest.
What goes on the wire
| Tier | Who | Rate | Bytes per tick, typical |
|---|---|---|---|
| Near, under 60 m or in view | 12 entities | 20 Hz | 12 x 9 = 108 B |
| Mid, 60-200 m | 25 entities | 10 Hz | 25 x 9 / 2 = 113 B |
| Far, over 200 m | 27 entities | 2 Hz | 27 x 9 / 10 = 24 B |
| Events, health change, teleport | any | immediate | 10-30 B |
Total is roughly 275 B per tick, 5.5 KB/s, leaving headroom for voice, events and a bad tick. The headroom matters. A budget that averages exactly 20 KB/s will spike past it when a fight starts.
Delta compression uses a per-client baseline, the last snapshot that client acknowledged. Each packet carries a baseline id, a dirty bitmask, and only changed fields. Unchanged entities cost one bit. If a packet is lost, the next packet still references the last acknowledged baseline, not the lost one, so the client can reconstruct. A full snapshot is forced every 2 seconds and on teleport, respawn or cell change, because a delta against a stale baseline after a teleport produces a huge, wrong correction.
// C++17, checked against a 64-entity snapshot
struct PackedEntity {
uint8_t id; // 0-63
uint16_t x, y, z; // cell-relative, 16 m cell
int8_t vx, vy, vz; // scaled to +/-32 m/s
uint8_t health; // 0-100
}; // 9 bytes, packed, no padding
uint16_t Quantize(float v, float origin, float cell) {
float t = (v - origin) / cell; // 0..1 inside cell
return (uint16_t)std::clamp(t * 65535.0f, 0.0f, 65535.0f);
}A worked trace
Tick 1024 is the baseline for client 7. Entity 17 moves 0.4 m, entity 40 does not move, entity 52 takes damage. The packet is 1 B baseline id, 8 B dirty mask for 64 entities, then 9 B for entity 17, 3 B for entity 52 (id plus health, position unchanged), and nothing for entity 40. Total 21 B plus header, against 576 B for a full quantized snapshot. The client applies it to its copy of baseline 1024. If that packet is lost, tick 1025 still deltas against 1024, so no error accumulates. If the client instead missed baseline 1024 itself, the server sees no ack for it and resends a full snapshot rather than stacking deltas on a baseline the client never got. That ack check is the failure mode people skip, and it shows up as entities snapping back or freezing after packet loss.
How I test it before shipping
I run a headless soak with 64 bots and a packet capture on the server socket, then replay the capture through a loss and jitter simulator at 0%, 2% and 5% loss with 40 ms jitter. I measure three things per client, not averages: bytes per second at p95 and p99, snapshot apply errors, and time for a far entity to become visible when it crosses into the near tier. Averages hide the fight spike. I also run a quantization check: place an entity at cell boundaries and at maximum velocity, confirm the reconstructed position error stays under 2 cm and velocity error under 0.5 m/s, because dead reckoning on the client extrapolates from those values between ticks. If error is larger, the client visibly rubber-bands when the next delta arrives.
Two failure modes get explicit tests. First, interest pop-in: an entity entering the near tier must arrive as a full entity, not a delta, or the client renders it at the origin for a tick. Second, MTU: I keep a packet under 1,200 B so it fits one UDP datagram on a 1,500 B MTU path. A 2 KB packet fragments, and losing one fragment loses the whole packet, which at 5% loss turns into a much higher effective loss rate. When p99 bandwidth still exceeds budget in a full fight, I do not lower the tick rate globally. I shrink the near radius from 60 m to 45 m and drop far entities to 1 Hz, because lowering the tick rate for everyone makes close combat feel laggy, which is the part players notice.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-80How would you design a data-driven ability system where designers tune cooldowns, costs and unlock conditions without code changes, and the game still rejects invalid casts cleanly?
The 90-second answer
Split the definition from the runtime state. Designers edit a data asset, the game loads it once, validates it, and creates a small runtime instance per character. A cast never reads raw designer fields directly. It asks the runtime instance, in a fixed order: is it unlocked, can the character pay the cost, is it off cooldown, then execute.
That order matters because each failure needs a different UI response. Locked shows a lock icon. Unaffordable shows a greyed cost. On cooldown shows a radial sweep and a number. If you collapse those into one boolean, the HUD cannot explain why the button did nothing.
// C# (Unity 2022 LTS, plain data, no engine types in the core)
public enum CostType { Mana, Stamina, Health }
[System.Serializable]
public struct AbilityDef
{
public string Id; // "fireball", stable across renames
public float Cooldown; // seconds, 0 = no cooldown
public int Charges; // 1 = single shot, >1 = stored charges
public float ChargeTime; // seconds per charge, used when Charges > 1
public CostType CostType;
public int Cost;
public string RequiredAbility; // "" = none
public int RequiredLevel;
public string RequiredFlag; // quest or story flag, "" = none
public float GlobalCooldown; // shared GCD applied to other abilities
}
public sealed class AbilityInstance
{
public AbilityDef Def;
public float CooldownLeft;
public int ChargesLeft;
public float ChargeTimer;
public bool Unlocked;
}AbilityDef is what ships in JSON, a ScriptableObject, or a spreadsheet export. AbilityInstance lives on the character and changes every frame. Saving a character saves instance state, never the definition, so a balance patch that changes Fireball from 6 s to 4 s applies to old saves without a migration.
Cast check and execution
public enum CastResult { Ok, Locked, NoMana, OnCooldown, NoCharges }
public CastResult TryCast(AbilityInstance a, Character c, float now)
{
if (!a.Unlocked) return CastResult.Locked;
if (c.GetResource(a.Def.CostType) < a.Def.Cost) return CastResult.NoMana;
if (a.ChargesLeft <= 0) return CastResult.NoCharges;
if (a.CooldownLeft > 0f) return CastResult.OnCooldown;
return CastResult.Ok;
}
public void Execute(AbilityInstance a, Character c)
{
c.Spend(a.Def.CostType, a.Def.Cost); // only after TryCast passed
a.ChargesLeft--;
if (a.ChargesLeft == a.Def.Charges - 1) a.ChargeTimer = a.Def.ChargeTime;
a.CooldownLeft = a.Def.Cooldown;
c.ApplyGlobalCooldown(a.Def.GlobalCooldown);
SpawnEffect(a.Def.Id, c);
}Ticking is explicit and pausable:
public void Tick(AbilityInstance a, float dt)
{
if (a.CooldownLeft > 0f) a.CooldownLeft = System.Math.Max(0f, a.CooldownLeft - dt);
if (a.ChargesLeft < a.Def.Charges)
{
a.ChargeTimer -= dt;
if (a.ChargeTimer <= 0f)
{
a.ChargesLeft++;
a.ChargeTimer = a.Def.ChargeTime;
}
}
}Call Tick only when the character is alive and the game is not paused. That single decision prevents the classic bug where cooldowns run during a death screen or a cutscene and the player returns with everything ready.
Worked trace
Fireball: cooldown 6 s, cost 30 mana, charges 1. Character has 100 mana. Global cooldown 0.5 s.
| Time | Event | State after |
|---|---|---|
| 0.0 s | Cast succeeds | mana 70, CooldownLeft 6.0, GCD 0.5 |
| 0.2 s | Player presses Fireball again | TryCast returns OnCooldown, no mana spent, HUD shows 5.8 s |
| 3.0 s | Player casts Frostbolt (GCD only) | GCD expired at 0.5 s, so it succeeds, mana 70 to 55 |
| 6.0 s | Cooldown reaches 0 | Next press succeeds, mana 55 to 25 |
A charge ability behaves differently. With 3 charges and 2 s per charge, casting twice leaves 1 charge and a timer at 2 s. After 2 s the timer refills to 2 charges, after another 2 s to 3. The cooldown field is unused in that mode, which is why the definition carries both and validation rejects a definition that sets both a long cooldown and multiple charges unless the design intends a hybrid.
Unlock conditions
Evaluate unlocks on events, not every frame. Level up, quest complete, and ability learned all call ReevaluateUnlocks(character). It walks the definitions in dependency order and sets Unlocked when level, flag, and prerequisite are all met. Prerequisite chains need a cycle check at load time. If A requires B and B requires A, neither ever unlocks and the player gets no error. Load validation catches it.
| Cooldown type | Use it for | Watch out for |
|---|---|---|
| Single cooldown | One cast, then wait | Cooldown ticking while dead or paused |
| Charges | Burst play, forgiving timing | Timer reset bug when casting at full charges |
| Global cooldown | Stops ability spam | Applying it to the ability that triggered it twice |
| Cost only, no cooldown | Basic attacks | Cost so low it never gates anything |
Failure modes I test for
Designer data is untrusted input. At load, reject negative cooldowns, negative costs, cost above the character maximum at the required level, charge time of zero with multiple charges, and unknown RequiredAbility ids. Log the asset name and field. A bad row should disable that one ability and show a placeholder in the editor, not crash the build.
The second failure is deducting cost before validation. If Execute runs and the effect spawn fails, the player paid for nothing. Keep the check and the spend adjacent, with no early return between them, and make Spend assert on insufficient resource in debug builds.
The third is UI desync. The HUD should poll TryCast or read the same instance fields the game uses, never keep its own cooldown timer. Two timers drift by a frame and the sweep finishes before the ability is actually ready, which players read as a bug even when the game is correct.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-81Walk me through designing an inventory system with item stacking, a weight limit, and save files that stay compatible when you add items and change stack sizes in a patch?
The 90-second answer
Separate three things that players and patches both touch: the item definition, the slot contents, and the save format. Definitions live in data, not code, and carry a stable string ID, maxStack, and weight. A slot holds only defId, count, and, for unique items, an instance ID for durability or mods. Weight and free space are derived from those slots on demand, never stored as truth in the save. The save stores a version, the slot list, and any unknown IDs verbatim, so a patch that adds an item or changes a stack size migrates instead of corrupting.
That split is what makes stacking, encumbrance, and loading independent. Change maxStack in data and stacking follows. Change weight in data and carry capacity follows. Add a new item and old saves still parse because they never stored a numeric index into an array that shifted.
Data model and stacking
// Checked against C# 12 / .NET 8 conventions. Definitions are data.
public sealed record ItemDef(string Id, int MaxStack, float Weight, bool Unique);
public struct Slot
{
public string DefId; // "arrow", "iron_sword", never an int index
public int Count; // 1..MaxStack, 0 means empty
public uint InstanceId; // 0 unless Unique, then persistent
}Add(defId, count) fills existing partial stacks first, then empty slots, and returns what did not fit. It never creates a stack above MaxStack, and it checks weight before committing, so a failed add leaves the inventory unchanged.
Worked trace, hypothetical figures: capacity 20 slots, carry limit 30.0 kg. Arrow: MaxStack 99, Weight 0.02 kg. Iron sword: MaxStack 1, Weight 3.5 kg, unique.
| Step | Action | Result |
|---|---|---|
| 1 | Add 150 arrows to empty inventory | Slot 0: 99, Slot 1: 51. Weight 3.0 kg, 18 slots free |
| 2 | Add 60 arrows | Slot 1 tops up to 99 (48 used), Slot 2: 12. Weight 4.2 kg |
| 3 | Add iron sword | Slot 3: sword, InstanceId 1042. Weight 7.7 kg |
| 4 | Try to add 2,500 arrows | Weight binds first: 22.3 kg left allows 1,115 arrows. That is 87 to top up Slot 2, 990 in 10 new slots, 38 in the next. Weight stops at 30.0 kg, 1,385 leftover, 15 of 20 slots used |
Filling partial stacks first matters for the UI and for save size. Without it, 150 arrows could scatter as 99 plus 51 in any order, and a later top-up would leave two partial stacks that waste slots and confuse sorting. In step 4 the slot limit alone would have allowed 1,671 arrows (87 plus 16 empty slots at 99), so weight, not slots, is the binding constraint there. Checking both limits before committing is what produces the correct leftover count.
Weight limit
Compute total weight as sum(def.Weight * slot.Count) over occupied slots. With a few hundred slots that loop is trivial, and it cannot drift from the contents. If you cache it for HUD updates, invalidate the cache on every mutation of a slot and recompute in the same function that mutates, not in a separate update pass that can be skipped.
Two failure modes show up in playtests. First, storing weight in the save: a balance patch halves arrow weight, the loaded save still carries the old total, and the player is suddenly under or over the limit with no visible cause. Second, checking weight per item instead of per add: each arrow is light, so a bulk loot action that adds 2,000 of them passes the per-item check and blows the limit. Check the projected total before the add, and make bulk operations atomic, either all of it fits or the player gets a partial result with a clear leftover count.
Encumbrance beyond a hard cap is a design choice, not a data problem. If over the limit should slow movement rather than block pickup, keep the same derived weight and expose IsOverweight to the movement code. Do not encode speed penalties into the inventory itself.
Save compatibility
Save a header and the slots, nothing derived:
{ "version": 3, "slots": [ {"id":"arrow","n":99}, {"id":"iron_sword","n":1,"inst":1042} ], "unknown": [] }Rules that keep a v1 save loading in v3:
- IDs are strings from data. Renaming an ID in data is a breaking change, so treat IDs as shipped API. If an item is removed, keep its definition as a tombstone or move its ID to
unknownon load. MaxStackandWeightare read from current data at load, not from the save. IfMaxStackdrops from 99 to 50, a saved stack of 99 splits into 50 plus 49 on load, and the split is reported in the migration log. If it rises, the stack stays as saved and merges on the next add.- Migration is a pure function
SaveV1 -> SaveV2 -> SaveV3with a test per step. Test with a golden save file checked into the repo, load it in the new build, and assert slot counts and total weight. A save that fails to parse loads into a backup slot and shows an error, it never overwrites the file in place. - Unknown IDs are preserved in
unknownrather than dropped. A modded item in a save loaded without the mod then survives a round trip, instead of vanishing the first time the player saves in vanilla.
The common break is storing the definition index. Add one item at the top of the data table in a patch and every saved slot now points at the wrong item, swords become potions, and the bug only appears in old saves. String IDs cost a few bytes per slot and remove that entire class of failure.
When not to use this shape
If items have per-instance state beyond durability, such as affixes or a crafting history, the slot needs a small instance record, not just a count. That is fine, but keep it optional and only allocate it for unique items. Giving every stackable an instance ID bloats the save and breaks stacking, because two stacks of arrows with different instance IDs no longer merge. The line is: stackables share state through the definition, uniques carry their own.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-82How would you track completed nodes in a dialogue graph so a player cannot revisit a finished branch, while still allowing a repeatable node?
The 90-second answer
Give every dialogue or quest node a stable ID and a kind, then keep a set of completed IDs separate from the graph itself. Before you enter a node, check the set. If the node is one-shot and already in the set, prune that edge and do not start it. When the player finishes the node, add its ID to the set. Repeatable nodes, like a shop hub or a hint giver, are never added, so they stay available.
That separation matters. The graph describes what can follow what. The completed set describes what this player has already done. You can save, load and test the second without rewriting the first.
public enum NodeKind { Once, Repeatable }
public sealed class DialogueNode
{
public int Id;
public NodeKind Kind;
public int[] NextIds;
}
public sealed class DialogueState
{
private readonly HashSet<int> completed = new();
public bool CanEnter(DialogueNode node) =>
node.Kind == NodeKind.Repeatable || !completed.Contains(node.Id);
public void Complete(DialogueNode node)
{
if (node.Kind == NodeKind.Once)
completed.Add(node.Id);
}
public int[] Save() => completed.ToArray();
public void Load(int[] ids) { completed.Clear(); completed.UnionWith(ids); }
}Traversal then becomes a guard at the edge, not a special case inside each node:
void Enter(DialogueNode node, DialogueState state)
{
if (!state.CanEnter(node)) return; // finished branch, skip it
Play(node);
state.Complete(node);
foreach (var next in node.NextIds)
Enter(nodes[next], state);
}Worked trace
Graph: 1 Start (Once) -> 2 Warning (Once) -> 3 Hub (Repeatable) -> 2, 4 Reward (Once)
| Step | Call | completed after | Result |
|---|---|---|---|
| 1 | Enter 1 | {1} | plays, moves to 2 |
| 2 | Enter 2 | {1,2} | plays, moves to 3 |
| 3 | Enter 3 | {1,2} | plays, tries 2 then 4 |
| 4 | Enter 2 again | {1,2} | CanEnter is false, pruned |
| 5 | Enter 4 | {1,2,4} | plays once |
| 6 | Return to 3 later | {1,2,4} | hub plays again, 2 and 4 both pruned |
The player can revisit the hub for new options without replaying the warning or claiming the reward twice.
Two details decide whether this holds up in play. First, mark completion on exit, not on entry. If the player quits, dies or the game crashes mid-node, the node is not in the set and can be replayed cleanly. Marking on entry would lock the branch even though the player never saw the outcome. Second, save the completed set with the quest, not with the scene. On load, Load restores exactly the IDs the player earned, so a reloaded save cannot reopen a finished branch.
For a small graph a HashSet<int> is fine. For a graph with IDs in a fixed range, say 0 to 255, a bool[] or a bitset is smaller and cache friendly, and CanEnter becomes an array lookup. The rule stays the same either way: check before entry, record on completion, exempt repeatable nodes.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-83With 8,000 enemies and objectives moving every frame, how would you use a uniform grid to find the nearest objective and all enemies within 12 metres, and how would you test it for correctness and frame cost?
The 90-second answer
Use a uniform grid with cell size equal to the largest common query radius, here 12 m. Insert each entity once into the cell containing its position. For a radius query, visit only cells intersecting the circle. For nearest, visit cells in expanding rings and stop when the closest possible point in the next ring is farther than the best candidate found. That early exit is the whole win, and it is also where most implementations go wrong.
Brute force for one query over 8,000 entities is 8,000 squared-distance checks. If 200 AI agents query every frame, that is 1.6 million checks per frame before any steering runs. With a 12 m cell in a 400 m by 400 m arena, the grid has about 34 by 34 cells. A 12 m query touches at most 9 cells. If density is roughly even, each cell holds about 7 entities, so the query checks about 60 candidates instead of 8,000.
// C++17, world bounded to [0, 4096) metres, cell = 12 m
constexpr float CELL = 12.0f;
constexpr int GRID = 342; // ceil(4096 / 12)
inline int cellIndex(float x, float z) {
int cx = std::clamp(int(x / CELL), 0, GRID - 1);
int cz = std::clamp(int(z / CELL), 0, GRID - 1);
return cz * GRID + cx;
}
// Each bucket stores entity ids. Moving entities update only on cell change:
// remove id from old bucket (swap-with-last), push to new bucket.
std::vector<std::vector<int>> buckets{GRID * GRID};For nearby enemies within 12 m, compute the cell range overlapped by the bounding square of the circle, clamp it to the grid, then test squared distance against 144.0f. No sqrt until you need a real distance for steering.
For nearest objective, do not just check the home cell and its neighbours and stop. A candidate 9 m away in the home cell does not prove nothing sits 10 m away across a border. Expand ring by ring. Before searching ring r, compute the minimum distance from the query point to any cell in that ring. If that minimum squared distance is greater than or equal to the current best, no later ring can win, so stop. Tie handling must be deterministic: keep the lower entity id on equal distance, or the brute force oracle and the grid will disagree in tests for no gameplay reason.
Worked trace, query at (100, 50), cell size 12:
| Step | Cells searched | Best found | Ring floor distance | Decision |
|---|---|---|---|---|
| 0 | cell (8, 4) | objective 17 at 9.0 m | 0 m | continue |
| 1 | 8 surrounding cells | objective 17 still best | 12.0 m | 12 > 9, stop |
The ring floor is the distance to the nearest edge of the next ring, not the distance to its centre. Using the centre overestimates the floor and can stop one ring early.
Cell size is a trade-off, not a constant to copy:
| Cell size | Effect |
|---|---|
| 6 m, half the query radius | Radius query touches about 25 cells, more bucket overhead, fewer false candidates per cell |
| 12 m, equal to radius | At most 9 cells per query, best for this query |
| 24 m, double the radius | 4 cells, but each cell holds roughly 4 times the entities, so distance checks climb |
If query radii vary widely, say 3 m for pickups and 40 m for artillery, one grid serves neither well. Use the grid for the common radius and a separate coarse grid or a second pass for the large radius, or insert large-radius queries as a cell range scan and accept the cost. Measure with the actual density. A cluster of 500 enemies in one cell defeats any cell size, and the fix there is gameplay density or a hierarchical grid, not tuning 12 to 10.
How I test it
Correctness first, against brute force as the oracle. Generate 10,000 random configurations with a fixed seed: random positions, entities on cell borders, entities exactly at the query radius, empty cells, and a query point outside the world bounds. For each, compare the grid nearest id and the full radius set against brute force. Any mismatch is a bug, usually a clamped cell index, a stale bucket entry after a teleport, or the ring floor mistake above. Teleports are the classic stale entry: if an entity jumps 200 m and the update path only runs on the movement code path, its old bucket still returns it. Route all position changes through one setPosition that updates the bucket.
Then performance, with the real query mix. Log per-frame query count, candidate checks, and p99 query time in a debug build. I want candidate checks per query in the tens, not hundreds, and p99 under about 0.05 ms for this workload. If p99 spikes, print the hottest cell occupancy. That tells me whether the problem is cell size or a genuine enemy pile-up.
Two failure modes to name in the interview. First, entities with a radius larger than a cell, such as a boss with a 20 m body radius. Inserting only by centre misses queries near its edge. Insert into every cell the body overlaps, or keep large entities in a separate short list checked every query. Second, duplicate entries after a swap-remove bug, where the moved id appears in two buckets and steering sees the same enemy twice. The oracle test catches this because the radius set will contain a duplicate or a phantom at the old position.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-84How would you test collision layers and masks so a bullet hits enemies but passes through pickups, and a player collides with the world but not with triggers?
The 90-second answer
Give every object one layer, meaning the category it belongs to, and one mask, meaning the layers it is willing to collide with. A pair collides only when both tests pass: A.mask contains B.layer and B.mask contains A.layer. That second check is the part people skip. If you test only one direction, a one-way mask silently becomes a two-way mask and you get bullets hitting pickups because the pickup happens to list bullets.
I would define layers as bit positions, not as sequential integers, and test the full pair matrix automatically rather than spot-checking the two cases I care about.
// Checked against C++17. Layers are bit positions.
enum Layer : uint32_t {
World = 1u << 0, // 1
Player = 1u << 1, // 2
Enemy = 1u << 2, // 4
Bullet = 1u << 3, // 8
Pickup = 1u << 4, // 16
Trigger = 1u << 5, // 32
};
struct Body {
uint32_t layer; // exactly one bit
uint32_t mask; // any combination of bits
};
bool CanCollide(const Body& a, const Body& b) {
return (a.mask & b.layer) != 0 && (b.mask & a.layer) != 0;
}With that rule, the setup for your scenario is:
| Body | Layer | Mask | Collides with |
|---|---|---|---|
| World | World | Player | Enemy | Bullet | player, enemy, bullet |
| Player | Player | World | Enemy | Pickup | world, enemy, pickup |
| Enemy | Enemy | World | Player | Bullet | world, player, bullet |
| Bullet | Bullet | World | Enemy | world, enemy |
| Pickup | Pickup | Player | player |
| Trigger | Trigger | 0 | nothing, sensor only |
Trace the pairs you named. Bullet versus enemy: bullet mask has Enemy, enemy mask has Bullet, both pass, contact fires. Bullet versus pickup: bullet mask lacks Pickup, so it fails at the first test and the bullet passes through. Player versus trigger: trigger mask is 0, so the second test fails even if the player mask lists Trigger. That is how I keep triggers as overlap-only volumes. I would not put triggers on the world layer and hope the solver treats them gently. A trigger that shares a layer with solid geometry will block movement in engines where the layer decides the response.
How I test it
I generate the matrix from the table above and run one test per unordered pair, including self-pairs. Each test spawns two static bodies overlapping by 1 cm, steps physics for a few fixed steps, and records whether a contact or overlap event fired. For 6 layers that is 21 pairs. The test fails if the observed result differs from CanCollide. I also add a negative test where I flip one bit in one mask and confirm the result flips. That catches the common bug where the engine or my code only checks one direction.
Two failure modes show up in production and are worth naming in the interview. First, assigning layer = 3 instead of layer = 1u << 3. The value 3 sets two bits, so the body suddenly belongs to two categories and collides with everything either category collides with. I assert (layer & (layer - 1)) == 0 in debug builds when a body is created. Second, running out of bits. With 32 layers you have 32 categories. A 33rd category created by shifting 1u << 32 is undefined behaviour on a 32-bit uint32_t. If a project needs more, I move to uint64_t before the shift overflows, not after a category starts misbehaving.
The trade-off is expressiveness against debuggability. A full matrix in the editor, as Unity exposes, is easy to read but symmetric by construction, so you cannot express "bullets hit enemies but enemies ignore bullets" without a separate rule. Per-body masks can express it, at the cost of a misconfigured mask on one prefab breaking a pair that looked correct in the matrix. That is why I treat the mask as data, review it in the pair test, and never hand-edit a layer value on a placed instance without rerunning that test.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-85How do you carry a player on a kinematic moving platform so they inherit its translation and rotation without sliding, jittering, or gaining extra speed when they jump?
The 90-second answer
Do not parent the player to the platform and do not rely on friction to drag them along. Move the kinematic platform first, compute the displacement of the point under the player for that step, and apply that displacement to the player before the player's own movement code runs. The player stays a free body, so jumping, slopes and knockback still work, but each frame they receive the platform's translation and the tangential motion from its rotation.
That gives you three pieces: a reliable standing test, a per-step platform delta, and a clean detach on jump.
Standing test and order
Probe down from the player's feet with a short shape cast, about 0.1 to 0.2 m beyond the capsule, and store the platform hit. Run this after the platform moves. If you probe before the platform moves, a fast platform leaves the probe behind and the player flickers between grounded and airborne, which shows up as jitter and lost carry.
Order per physics step:
- Move platform from transform A to transform B.
- Compute rider delta from A to B.
- Move rider by that delta.
- Run player input, gravity and collision as normal.
Computing the delta, including rotation
Translation alone is not enough. A rider 1 m from the centre of a platform rotating at 90 degrees per second (1.57 rad/s) moves tangentially at 1.57 m/s even if the centre does not translate.
// Unity 2022 LTS, C#, called in FixedUpdate after the platform moves
Vector3 localBefore = platform.worldToLocalMatrix.MultiplyPoint(playerFeet);
// platform has now moved to its new transform
Vector3 worldAfter = platform.localToWorldMatrix.MultiplyPoint(localBefore);
Vector3 platformDelta = worldAfter - playerFeet;
player.position += platformDelta; // carry, before player velocity is applied
float platformSpeed = platformDelta.magnitude / Time.fixedDeltaTime;Using the player's feet point, not the platform centre, captures translation and rotation in one subtraction. It also handles a platform that both translates and rotates, and one that moves on a curved path, with no separate angular velocity math in gameplay code.
Worked trace, hypothetical figures: platform moves right at 2 m/s, fixed step 1/60 s. Per step the centre moves 0.033 m. A rider standing still in world space would end the step 0.033 m behind the deck, the ground probe would still hit for a few frames, then the rider would appear to slide backwards and eventually walk off the rear edge. With the delta above, the rider also moves 0.033 m right, relative position on the deck is unchanged, and the player's own velocity is untouched.
Jumping off and downward platforms
On jump, detach before adding jump velocity. Decide explicitly whether the jump keeps platform momentum. Most platformers add the platform's horizontal velocity to the jump so a jump from a fast platform carries forward, then stop applying carry once airborne. If you keep applying the delta while airborne, the player is glued to the platform and cannot jump off sideways.
A platform moving down faster than gravity pulls the player is the classic failure. The deck drops away, the probe misses, the player goes airborne for a frame, lands with a thud, and repeats. Fix it with the carry step above plus a small downward snap while grounded: keep the probe length at least platformDownSpeed * dt plus a margin, and apply gravity normally after the carry. Test at the fastest descent you ship, not at a comfortable speed.
Why not the alternatives
| Approach | What happens | When it fails |
|---|---|---|
| Parent player to platform | Zero relative motion, trivial carry | Player inherits scale and rotation in their own transform, jumping and wall checks break, physics fights the parent |
| Friction only | Ground friction drags player with deck | Lags by a frame or more, slides on low friction materials, fails completely on vertical or rotating decks |
| Delta carry, player unparented | Player moves with deck, stays independent | Needs a correct standing test and a cap on delta size |
Cap the delta. If a platform teleports or a streaming hitch moves it 5 m in one step, applying the full delta launches the rider. Clamp carry to a sane maximum per step, or treat a teleport as a detach and re-place riders explicitly. That one check prevents the most embarrassing bug in this system, the player flung across the level when a lift resets.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-86How would you use a trigger volume and a boolean to make a pressure plate open a door only while something is standing on it?
The 90-second answer
Give the plate a trigger collider with isTrigger set, and keep a set of the colliders currently inside it. The plate is pressed when that set is non-empty. The door reads that one boolean each frame and moves toward open or closed accordingly. A single boolean toggled on enter and exit breaks as soon as two objects are involved, because the first exit clears it while the second object is still standing there.
// Unity 2022 LTS, C# 9. Attach to the plate. The collider must be a trigger.
public class PressurePlate : MonoBehaviour
{
private readonly HashSet<Collider> occupants = new();
public bool IsPressed => occupants.Count > 0;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Pressable"))
occupants.Add(other);
}
private void OnTriggerExit(Collider other)
{
occupants.Remove(other);
}
private void Update()
{
// A destroyed collider does not reliably send OnTriggerExit.
// In Unity it becomes null, so prune it here.
occupants.RemoveWhere(c => c == null);
}
private void OnDisable()
{
occupants.Clear();
}
}The door does not need to know about triggers at all. It stores its closed position once and offsets from there, so it works wherever the designer placed it in the level:
public class PressureDoor : MonoBehaviour
{
public PressurePlate plate;
public float openHeight = 2.5f;
private Vector3 closedPos;
private float t; // 0 = closed, 1 = open
private void Start()
{
closedPos = transform.position;
}
private void Update()
{
float target = plate.IsPressed ? 1f : 0f;
t = Mathf.MoveTowards(t, target, Time.deltaTime / 1.2f); // 1.2 s travel
transform.position = closedPos + Vector3.up * (openHeight * t);
}
}Trace
| Frame event | occupants | IsPressed | Door |
|---|---|---|---|
| Player enters | {Player} | true | starts opening |
| Crate enters | {Player, Crate} | true | stays open |
| Player exits | {Crate} | true | stays open |
| Crate exits | {} | false | starts closing |
| Crate destroyed on plate | {null} until next Update, then {} | false after prune | closes |
That middle row is the test that catches the naive version. With OnEnter: pressed = true and OnExit: pressed = false, the player stepping off would close the door on the crate.
Failure modes I test for
Tag filtering matters. Without the Pressable check, a particle effect, a camera collider or a stray projectile holds the door open. I decide the list up front: player, movable crates, maybe a specific enemy. Everything else is ignored.
Exit is not guaranteed. Teleporting an object out, disabling it, or destroying it inside the volume can skip OnTriggerExit depending on the engine and how the object is removed. The Update prune covers the destroyed case, because a destroyed Unity object compares equal to null. OnDisable on the plate itself is a separate case: if the plate is disabled, its own set should not leak into a later re-enable. A plain counter (count++ on enter, count-- on exit) has the same problem and adds another one: a duplicate enter event drives it negative or leaves it stuck above zero. The set makes duplicate enters harmless.
Physics timing is the last one. Trigger callbacks arrive during the physics step, so a fast object can enter and leave between rendered frames, or tunnel through a thin plate entirely. If the plate is thin and objects move fast, I make the trigger volume taller than the fastest object travels per step, or use a swept check, rather than trusting the callbacks at 20 fps.
For a test pass I walk the player on and off, drop two crates on, remove one, destroy one while it stands there, and teleport the player away. The door should open once, stay open through the overlaps, and close only when the set is empty. If it flickers, the usual cause is two plates writing to the same door, or the door reading the boolean before the physics step has run that frame, so I log IsPressed alongside the occupant count for one playthrough and compare it against the trace above.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-87Walk me through how you would implement respawn at a checkpoint so enemies and projectiles reset to their spawn state while player health, inventory and progress survive, and how you would test it?
The 90-second answer
I treat respawn as restoring two different snapshots taken at the checkpoint, not as reloading the whole level. The checkpoint captures a player snapshot and an enemy/world snapshot separately. On death I restore the player snapshot, restore the enemy snapshot, and clear transient state that belongs to neither. That separation is the whole design. If I reload the level, I lose progress made after the checkpoint. If I only move the player back, enemies stay dead, damaged, or alerted, and the player can farm or skip content.
Assume a single-player action game, checkpoint at a door, player dies to a patrol. I need to preserve health at checkpoint value, inventory, XP, unlocked abilities, and quest flags set before the checkpoint. I need to reset enemy position, health, state, and timers, remove projectiles and particles, and reset triggers that fired after the checkpoint.
// C# / Unity-style, checked against Unity 2022 LTS patterns
public struct PlayerSnapshot {
public Vector3 Position; public float Health;
public int InventoryVersion; public int Xp;
public BitArray QuestFlags; // copied, not referenced
}
public struct EnemySnapshot {
public int EnemyId; public Vector3 SpawnPos;
public float Health; public int State; // Idle, Patrol, Chase
public float ThinkTimer;
}
public sealed class Checkpoint {
public PlayerSnapshot Player;
public EnemySnapshot[] Enemies;
public int RngState; public int WorldTick;
}Capture copies values. For QuestFlags I clone the array. Storing a reference would let later progress mutate the checkpoint, so dying after picking up a key would keep the key in the checkpoint and break the reset.
Restore order
- Freeze gameplay input and AI ticks for one frame. Stop the spawner and projectile pool.
- Destroy live projectiles, particles, and temporary physics bodies. Returning them to pools without resetting velocity leaves a pooled bullet flying from the death position.
- Restore each enemy from
EnemySnapshot: teleport toSpawnPos, set health, set state toIdleorPatrol, clear target, clear blackboard entries written after the checkpoint, resetThinkTimerto the captured value. - Restore the player from
PlayerSnapshot: position, health, inventory version, XP. Do not restore position from the enemy list or health from the live player. - Restore
RngStateandWorldTick. Without this, patrol routes and loot rolls diverge on every retry and a player can reroll a drop by dying. - Re-register triggers and event subscriptions that were consumed after the checkpoint. A one-shot trigger that opened a gate after the checkpoint must fire again, or the gate stays open while enemies reset.
| State | On respawn | Why |
|---|---|---|
| Player position, health, XP, inventory | Restore checkpoint values | Progress before checkpoint survives |
| Enemy position, health, state, timers | Restore spawn snapshot | Encounter restarts fairly |
| Projectiles, particles, damage numbers | Destroy or pool-reset | They belong to the failed attempt |
| RNG state, world tick | Restore captured values | Patrols and drops repeat deterministically |
| Quest flags set after checkpoint | Revert to captured copy | Prevents farming and skipped gates |
| Pickups collected after checkpoint | Respawn them | Otherwise the player loses items with no way to recover |
Worked trace
Checkpoint at tick 1000: player health 80, XP 1200, has Key A. Enemy 7 at spawn, health 50, state Patrol, think timer 0.4 s. RNG state 9917.
Player kills Enemy 7, takes damage to health 10, picks up Key B, opens a gate, then dies at tick 1400. Live state now has Enemy 7 dead, Key B consumed, gate open, RNG state 10402.
Restore sets player health to 80 and position to the checkpoint, Enemy 7 to health 50 at spawn in Patrol with timer 0.4 s, respawns Key B, closes the gate, and sets RNG state back to 9917. The next patrol roll matches the first attempt. If I had only teleported the player, Enemy 7 would stay dead and the gate would stay open, so the player would walk through a cleared encounter with full checkpoint health.
Failure modes I test for
Stale AI references: an enemy restored to Patrol still holds a target pointer to the player death position. I clear targets on restore and add a test where an enemy chases, the player dies, and after respawn the enemy returns to its patrol route within one think tick instead of running to the corpse.
Double subscription: respawn re-runs OnEnable on pooled enemies without unsubscribing, so health changes fire the HUD twice. I count handler invocations in an automated test after three respawns. The count must stay at one per event.
Snapshot aliasing: the checkpoint stores the live inventory list. Picking up an item after the checkpoint changes the checkpoint. I test by mutating live inventory, respawning, and asserting the restored inventory equals the captured version.
Physics residue: a restored enemy keeps velocity from the chase. I set velocity to zero on restore and test that a restored enemy does not slide off a ledge in the first physics step.
I run the suite at 30, 60, and 144 Hz. Respawn must produce the same enemy positions and RNG sequence regardless of frame rate, because restore happens from captured values, not from integrating the failed attempt.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-88How would you use a sphere cast to stop a third-person camera clipping through walls, and why choose it over a simple ray cast?
The 90-second answer
Cast a sphere from the character pivot toward the desired camera position, after the character has moved and before rendering. The sphere radius matches the camera collision radius, about 0.3 m for a third-person boom, and the cast length is the full boom length. If the cast hits, place the camera at the hit distance minus a small margin. If it misses, place it at full length.
A ray cast tests a line with no width. It can report a clear path while the camera body, or its near plane, still intersects a wall corner. A sphere cast sweeps that volume, so the first contact accounts for the camera radius against the geometry. That is the main trade-off: the sphere cast costs a little more per query and needs a radius to tune, but it prevents the common case where a ray slips past a thin partition or a door frame and the camera ends up inside the wall.
// C++ style, using a PhysX or Jolt style sphere cast query
Vec3 pivot = player.HeadPosition();
Vec3 desired = pivot + boomDirection * boomLength;
Vec3 dir = (desired - pivot).Normalized();
Hit hit = Physics::SphereCast(pivot, 0.30f, dir, boomLength, worldMask);
float distance = hit ? hit.distance - 0.05f : boomLength;
Vec3 cameraPos = pivot + dir * std::max(distance, 0.0f);Run this in LateUpdate in Unity, or after the pawn update in Unreal. Running it in Update can use last frame's player position, so the camera lags behind a moving wall for a frame.
Worked trace
Boom length 4.5 m, sphere radius 0.30 m, margin 0.05 m. The player backs toward a wall and the cast first contacts it at 2.1 m.
| Case | Cast result | Camera distance |
|---|---|---|
| Wall 2.1 m behind pivot | Hit at 2.1 m | 2.05 m |
| No wall in range | No hit | 4.5 m |
| Wall 0.35 m behind pivot | Hit at 0.35 m | 0.30 m, clamped minimum |
Pull the camera in immediately when the new distance is shorter. Ease it back out when the distance grows, for example current += (target - current) * (1 - exp(-12 * dt)). Snapping in avoids clipping for several frames while easing in. Easing out avoids a pop when the player turns away from the wall. The eased target is already the safe distance, so easing out cannot overshoot into the wall.
Two edge cases are worth handling. If the hit is very close, under about 0.4 m, the wall can fill the screen even though the sphere centre is clear. Clamp the minimum distance and fade the player mesh for that frame rather than pushing the camera into the player's head. If the pivot starts inside geometry, after a teleport or a streaming pop-in, some engines report no hit or a zero distance. Test for overlap at the pivot and hold the camera at the pivot for that frame instead of returning full length.
The mask matters as much as the cast. Include static world and large props, exclude the player capsule and trigger volumes. Including the player makes the cast hit at zero every frame. Excluding props lets the camera clip through a crate the player knocked over.
To test it, build a corridor with a 0.1 m partition and walk backwards through a doorway while drawing the camera sphere in debug view. Record the camera position at 30, 60 and 144 Hz and check the sphere never overlaps the partition. That catches the one-frame clip that is easy to miss in playtesting.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-89A level chunk takes 10 ms to finalise on the main thread. How would you split that work across frames to avoid a hitch, and how would you test the split?
The 90-second answer
I would keep disk reading and decompression on worker threads and time slice only the main thread finalisation. Assume 60 fps, so a frame has 16.6 ms. If gameplay and rendering already use about 13 ms, I give chunk finalisation 2 ms per frame. A chunk that needs 10 ms of main thread work then takes five frames to appear, instead of adding 10 ms to one frame and dropping it to about 40 fps.
The split works because most finalisation is a loop over items. Deserialising objects, creating collision shapes and uploading buffers can stop after each item, check the clock, and resume next frame. Work that cannot be split, such as one large texture upload, has to be made smaller or moved to a staging buffer before it reaches the main thread.
The mechanism
// C++17. Workers fill readyQueue. Main thread drains it within a budget.
void FinaliseReady(std::queue<ChunkJob>& ready, double budgetMs) {
auto start = Clock::now();
while (!ready.empty()) {
ChunkJob& job = ready.front();
// Process one object, one mesh or one collider at a time.
bool done = FinaliseOneStep(job);
if (done) ready.pop();
if (ElapsedMs(start) >= budgetMs) break; // resume next frame
}
}FinaliseOneStep keeps its index inside the job, so stopping mid chunk loses no progress. Jobs are queued by distance to the player, nearest first. If the player turns around, jobs behind the player are cancelled before they consume budget.
| Approach | Main thread cost per chunk | Trade off |
|---|---|---|
| Load synchronously on demand | Full 10 ms in one frame | Simple code, visible hitch when the chunk is needed |
| Async read, unsliced finalise | Still 10 ms in one frame | Disk no longer blocks, hitch remains |
| Async read, sliced finalise | 2 ms per frame for five frames | Chunk appears later, frame time stays flat |
Worked trace
Hypothetical figures: a chunk needs 10 ms to finalise. Without slicing, a normal 14 ms frame becomes 24 ms. With a 2 ms budget, the same chunk is processed in five steps of 2 ms. Frame times stay near 14 to 16 ms, and the chunk becomes visible after about 80 ms of game time. If the player is standing on the chunk, I raise its priority and allow a one frame exception, because a hole under the player is worse than a single longer frame.
How I test it
I instrument frame time and record the maximum frame time while the player moves at full speed across a test level with forced chunk loads. I also log how many finalisation steps ran per frame and the queue depth. The test passes if no frame exceeds 20 ms during streaming and the queue drains within a set distance behind the player.
I run the test with a fake disk that adds a fixed delay, so results are repeatable in CI, then repeat it on the slowest target machine with real storage. Two failures show up quickly. A single unsplittable upload breaks the budget every time, which tells me to split the asset or upload it in pieces. A queue that keeps growing while moving tells me workers cannot keep up, which is a streaming distance or chunk size problem, not a slicing problem.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-90Why do shader compilation hitches happen mid-game, and how do you cut shader variants or precompile them to stop them?
The 90-second answer
A shader hitch happens because the GPU driver compiles a shader variant on first use, on the render thread, in the middle of a frame. The source you wrote is not what the GPU runs. The driver translates it to machine code for that exact GPU and driver version, and that translation can take tens to hundreds of milliseconds. If the player reaches a new material, light type or keyword combination for the first time, that compile lands inside the frame that first draws it.
You fix it two ways. Cut the number of variants so there is less to compile, and compile the variants you keep before gameplay starts, during loading or in the background.
Why variants multiply
One shader file becomes many programs. Every keyword combination is a separate program. A lit surface shader with fog, instancing, skinning, three lightmap modes and four shadow modes does not have 10 variants. It has the product.
| Keyword group | Options | Running total |
|---|---|---|
| Base pass | 1 | 1 |
| Fog on/off | 2 | 2 |
| Instancing on/off | 2 | 4 |
| Skinning on/off | 2 | 8 |
| Lightmap mode | 4 | 32 |
| Shadow mode | 4 | 128 |
That is a hypothetical but realistic count for one shader. Multiply by the number of shaders in the project and you get the build time, the install size and the warmup time. Stripping unused combinations in the build settings is usually the biggest win, because most of those 128 programs are never drawn.
Trace of a hitch
Hypothetical figures from a typical profile capture:
Frame 1842 16.4 ms normal draw of known variant
Frame 1843 142 ms first draw of FOG + INSTANCING + SHADOW variant
RenderThread: vkCreateGraphicsPipelines 118 ms
CPU submit and draw 9 ms
Frame 1844 16.1 ms same variant, now cached, no compileThe spike is not the draw. It is pipeline creation. On the next run on a different GPU or driver, the cache is cold again, so shipping a compiled binary does not remove the problem by itself.
Precompiling in practice
In Unity, collect the variants you actually use into a ShaderVariantCollection and warm it up on a loading screen:
// Unity 2022 LTS / Unity 6, C#
public class ShaderWarmup : MonoBehaviour
{
public ShaderVariantCollection variants;
IEnumerator Start()
{
AsyncOperation op = variants.WarmUpAsync();
while (!op.isDone) yield return null;
SceneManager.LoadSceneAsync("Level1");
}
}Unreal does the equivalent with a PSO cache file shipped with the game and precache calls for materials used in a level. In raw Vulkan or Direct3D 12 you create the pipelines during loading, or use a pipeline cache and asynchronous pipeline creation, and you keep the cache file with the build. The principle is the same in each engine. Pay the compile cost before the player can trigger it.
Cutting variants without losing features
Use shader features for combinations that are rare, so the compiler only builds them if a material in the project uses them. Strip keywords for platforms, light types and fog modes the game never uses. Replace a keyword that only changes a uniform value with a uniform. A tint or a toggle that can be a constant buffer value should not be a keyword.
The trade-off is load time and memory. Warming up 2,000 variants at 20 ms each is 40 seconds of compile work if done serially, so you spread it over loading screens, compile in the background where the engine allows it, and only warm up the variants for the next level. Precompiling everything in the project just moves the hitch to the title screen.
Two failure modes catch people out. A variant collection built on the development machine misses a dynamic keyword set at runtime, such as a light probe mode that only appears in a later level, so the hitch returns there. And a driver update or a new GPU invalidates the cached pipelines, so the first session after the update is slow again even with a shipped cache. Both are why you log pipeline creation time in development builds and test warmup on the lowest spec GPU you support, not just on your machine.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-91How would you test a shipped mobile build against device memory limits and choose between ETC2 and ASTC texture compression without blowing the frame or load budget?
The 90-second answer
I test on the lowest-spec devices we claim to support, not on a flagship, and I measure two separate budgets: CPU memory (PSS/RSS) and GPU texture memory. A build can pass one and be killed for the other. I run a scripted soak that loads every level, forces a memory warning, backgrounds and foregrounds the app, then checks that we survive without a jetsam or low-memory-kill and that frame time stays inside budget. For textures I ship per-platform variants from the same source art: ETC2 as the Android baseline, ASTC where the device supports it, and I never ship a desktop BC7 build to a phone hoping the driver will cope.
Why the format choice is a memory and a compatibility decision
Uncompressed RGBA8 at 2048x2048 is 16 MiB for one texture. That number decides whether a level fits.
| Format | Bits per pixel | 2048x2048 | Notes |
|---|---|---|---|
| RGBA8 uncompressed | 32 | 16.0 MiB | Debug only on mobile |
| ETC2 RGB | 4 | 2.0 MiB | Core in OpenGL ES 3.0, safe Android baseline |
| ETC2 RGBA | 4 | 2.0 MiB | Alpha in separate block, watch banding on gradients |
| ASTC 4x4 | 8.0 | 4.0 MiB | Highest quality ASTC block, still larger than ETC2 |
| ASTC 6x6 | 3.56 | 1.78 MiB | Good default for albedo and UI |
| ASTC 8x8 | 2.0 | 1.0 MiB | More artefacts, good for diffuse albedo |
| PVRTC 4bpp | 4 | 2.0 MiB | Legacy PowerVR only, do not target for new builds |
ASTC bits per pixel is 128 divided by the block pixel count, so 4x4 is 8 bpp, 6x6 is 3.56 bpp and 8x8 is 2 bpp. Add the mip chain and multiply by 1.33. A 2048 texture with full mips is 21.3 MiB uncompressed, 2.66 MiB in ETC2, 2.37 MiB in ASTC 6x6 and 1.33 MiB in ASTC 8x8. That 33% is not optional. Dropping small mips saves memory and then distant geometry shimmers and aliases, which is worse than the saving.
ASTC is smaller and higher quality at the same bit rate, but support is not universal on old Android GPUs. If I ship ASTC only, those devices either fail to load the texture or fall back through a slow CPU transcode I did not budget for. The safe split is: ASTC variant for devices reporting the extension, ETC2 variant for the rest, selected at build time by device tier, not at runtime by hoping. On iOS, ASTC and PVRTC are both available through Metal, but I still ship ASTC because PVRTC tooling and quality control are a dead end.
Worked budget, labelled as an example
Suppose the target is a 3 GB Android device and our internal cap is 900 MB PSS in the heaviest level, with 250 MB of that for textures including mips.
// Checked against Unity 2022.3 / Unreal 5.3 import settings in CI
long TextureBytes(int w, int h, double bitsPerPixel, bool mips)
{
double bytes = w * h * bitsPerPixel / 8.0;
return (long)(mips ? bytes * 1.33 : bytes);
}
// 2048x2048 ETC2 with mips: 2.66 MiB
// 2048x2048 ASTC 6x6 with mips: 2.37 MiB
// 2048x2048 ASTC 8x8 with mips: 1.33 MiB
// 120 such textures: 319 MiB (ETC2) vs 284 MiB (ASTC 6x6)
// vs 160 MiB (ASTC 8x8). ETC2 and 6x6 both exceed the
// 250 MiB texture cap; 8x8 for diffuse albedo brings it under.That trace is why I audit the build, not the editor scene. I dump the shipped APK/IPA, list every texture by platform variant and decoded size, and fail CI if the total exceeds the cap for the tier.
How I test it on device
- Cold start on the low tier device with a memory profiler attached. Record PSS, native heap, and GPU memory at menu, level load, peak combat, and after a forced
onTrimMemoryor iOS memory warning. On Android I usedumpsys meminfo <package>and the Android Profiler. On iOS I use Xcode Memory Gauge and Instruments Allocations, and I read the jetsam event log after a kill. - Soak loop: load level A, B, C in sequence ten times without restarting. PSS should plateau. Growth of 5 to 10 MB per cycle means a leak or a texture not being released on unload, and that is the usual cause of a kill an hour into a session rather than at load.
- Pressure test: background the app mid-level, open a heavy app, return. iOS may have reclaimed our textures. If we return with black textures or a crash on re-upload, the restore path is broken.
- Frame check under pressure: capture with RenderDoc on Android or Xcode frame capture on iOS at the moment PSS peaks. If texture memory pushed us into swap on Android or into a jetsam warning on iOS, frame time will show it as a hitch on streaming, not as a steady slowdown.
Failure modes I look for specifically: an sRGB flag mismatch that makes ASTC look washed out after compression, ETC2 punchthrough alpha turning soft particles into hard-edged sprites, NPOT textures without mips on a format that requires them, and a texture variant missing for one platform so the importer silently ships the uncompressed source. Each of those passes in the editor and fails only in the shipped build, which is why the audit runs on the build artifact itself.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-92How would you test a fixed memory pool for a console build so it never exceeds its deterministic budget or corrupts neighbouring allocations?
The 90-second answer
I treat the pool as a fixed contract: a known byte budget, a known maximum live count, and a known failure behaviour when that count is exceeded. On console that contract matters because the OS gives the title a fixed memory partition and a heap overrun can take down the whole frame, so the test has to prove three things. The pool never writes outside its arena, it never hands out the same slot twice, and under the worst gameplay load it stays inside budget with a measured margin.
Assume a particle pool on a console build: 8,192 slots, 64 bytes per particle, 16-byte alignment for SIMD writes. That is 512 KiB of payload. Add a free-list index array of 8,192 uint16_t entries, 16 KiB, plus guard bytes and a header. The shipped budget is 544 KiB. I would not accept a design that cannot state that arithmetic up front.
How I test it
First, a debug build wraps the arena with canaries and poisons freed slots. Every allocation checks alignment, bounds and the canary on release. A test that writes one byte past the last slot, or frees the same slot twice, must trip an assert in debug and be caught by the canary in release test builds.
// Checked against C++17, MSVC and Clang console toolchains.
template <typename T, size_t N>
class FixedPool {
alignas(16) T storage_[N];
uint16_t free_[N];
uint16_t freeCount_ = N;
uint16_t highWater_ = 0;
public:
FixedPool() {
for (size_t i = 0; i < N; ++i) free_[i] = uint16_t(N - 1 - i);
}
T* acquire() {
if (freeCount_ == 0) return nullptr; // deterministic failure, no heap fallback
T* p = &storage_[free_[--freeCount_]];
highWater_ = std::max(highWater_, uint16_t(N - freeCount_));
return p;
}
void release(T* p) {
// Bounds, alignment and double-free checks live here in test builds.
free_[freeCount_++] = uint16_t(p - storage_);
}
uint16_t highWater() const { return highWater_; }
};The key detail is the failure path. acquire() returns nullptr at exhaustion. The caller decides whether to drop the spawn, recycle the oldest particle, or degrade the effect. Falling back to new inside a frame would break the budget and reintroduce the hitch the pool exists to remove.
Second, I run a deterministic soak. A scripted sequence allocates and frees in a fixed pattern, including a 10,000-particle burst against an 8,192-slot pool, interleaved alloc and free to create fragmentation, and a worst-case level where every system that shares the pool fires at once. Because the sequence is seeded, the same run must produce the same high-water mark and the same exhaustion count on every machine. I record high-water mark, exhaustion count, and total bytes requested versus bytes granted.
| Test | Injection | Pass criterion |
|---|---|---|
| Exhaustion | Request 10,000 slots from an 8,192 pool | 8,192 granted, 1,808 return nullptr, no heap call |
| Overflow | Write 1 byte past slot 0 and past the final slot | Canary trips on release, assert fires in debug |
| Double release | Release the same pointer twice | Detected, second release rejected |
| Alignment | Request slots for a 16-byte SIMD struct | Every returned pointer is 16-byte aligned |
| Fragmentation | 50,000 interleaved alloc/free cycles | No slot handed out twice, free count returns to 8,192 |
| Budget | Worst-case scripted level load | High-water mark at or below 7,400 slots, leaving 10% headroom |
Third, I check lifetime. A pool that reuses raw storage must call destructors on release and placement-new on acquire for non-trivial types, or the pool must be restricted to trivially destructible structs and that restriction documented. A test with a type that counts constructions and destructions catches a pool that leaks or double-destroys.
Failure modes I watch for
The common one is silent corruption. Without guard bytes, an off-by-one write lands in the next slot and the bug surfaces frames later as a particle with a NaN position. The canary test catches it at the release that follows the write.
The second is budget creep. Someone adds a field to the particle struct, the slot grows from 64 to 80 bytes, and the pool silently exceeds its partition. A static assert on sizeof(T) and a build-time check that N * sizeof(T) plus overhead stays under the budget stops that at compile time.
The third is exhaustion handling that allocates. If the burst path calls a heap allocator when the pool is dry, the frame that needed the pool most is the frame that hitches. The soak test counts heap allocations during the burst and requires zero.
I would ship when the soak passes with the same numbers on dev kit and on the target hardware, the canary tests trip on every injected corruption, and the high-water mark from the worst scripted scene leaves headroom for a designer to push particle counts up without touching code.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-93A late-joining client connects mid-match. How would you order replicated spawns so a turret attached to a vehicle arrives after the vehicle and gets valid state?
The 90-second answer
I would send a late joiner a snapshot in dependency order, in two phases per object. First spawn every object, then send its initial state. Within the spawn phase, a parent, owner, or referenced actor always goes before the object that depends on it. So the vehicle spawns before the turret attached to it, and the character spawns before a weapon that character owns.
That order is what makes the state valid. A client cannot attach a turret to a transform that does not exist yet, and it cannot apply health or ammo values to an object it has not created. If state arrives first, the spawn code will usually overwrite it with defaults, and the object will look wrong until the next update.
How I would implement it
At spawn time on the server, each replicated object records one dependency: its parent, its owner, or the actor it attaches to. Most objects have at most one. I then sort the snapshot by dependency depth, which is just how many hops sit between the object and a root object with no dependency.
// Server side, C++20. Depth is computed once when the object spawns.
struct SpawnEntry {
NetId id;
NetId dependsOn; // kInvalidId for a root object
int depth; // 0 for roots, parent depth + 1 otherwise
int priority; // lower value sends earlier at the same depth
};
std::vector<SpawnEntry> snapshot = CollectRelevantObjects(client);
std::sort(snapshot.begin(), snapshot.end(), [](const SpawnEntry& a, const SpawnEntry& b) {
if (a.depth != b.depth) return a.depth < b.depth;
if (a.priority != b.priority) return a.priority < b.priority;
return a.id < b.id;
});
for (const auto& e : snapshot) SendSpawn(client, e.id);
for (const auto& e : snapshot) SendInitialState(client, e.id);The client side is simple. A spawn message creates the object. A state message for an ID that has not spawned yet is dropped and counted. In a correct snapshot that counter should stay at zero, so it is a useful test signal.
Worked trace
A match has a player pawn P07, a vehicle V10 owned by P07, and a turret T22 attached to V10. A client joins late.
| Step | Message | Result on the client |
|---|---|---|
| 1 | Spawn P07, depth 0 | Pawn exists with default values |
| 2 | Spawn V10, depth 1, owner P07 | Vehicle exists and ownership resolves |
| 3 | Spawn T22, depth 2, attached to V10 | Turret attaches to a real transform |
| 4 | Initial state for P07 | Health and position set once |
| 5 | Initial state for V10 | Fuel and damage set once |
| 6 | Initial state for T22 | Turret angle set on a live object |
| 7 | Live updates from here on | Deltas and RPCs find live objects |
Reverse steps 3 and 5 and the turret angle is written to an object that does not exist, then lost when the turret spawns with its default angle. That is the bug this ordering prevents.
The main trade-off
The alternative is to send objects in whatever order the server happens to store them, which is cheaper to code. It fails as soon as a child arrives before its parent, and the failure is intermittent because it depends on storage order. Sorting by depth costs a small sort at join time, typically a few hundred objects, and it makes the order deterministic. I would also sort by priority within a depth so player pawns and nearby enemies go before distant props, which lets the client show a playable scene sooner.
To test it, I run a headless server, join a client late, and assert that every spawn arrives after its dependency and that no initial state message targets an unspawned ID. I also check the final state of the turret angle against the server value, since that catches the overwrite bug even when nothing crashes.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-94How do you test that cheat codes and debug flags are fully removed from a shipped build, and what happens if you leave them in?
The 90-second answer
A cheat that ships is a cheat that gets found. Players dump strings from the binary within hours, and any input sequence, console command or debug flag left in the build becomes a feature they can trigger at will. So I do not just hide cheats behind a flag. I compile them out of the shipping configuration, then I test the shipping binary itself, not the editor build, for the strings, symbols and behaviours that would prove they survived.
In C++ that usually means a single shipping define controls every cheat path, and the cheat code is not referenced at all when it is set:
// CheatCodes.cpp, checked against MSVC 19.4x / Clang 17
#if defined(SHIPPING_BUILD)
void RegisterCheats() {} // no cheat strings, no handlers linked
#else
void RegisterCheats() {
Input::BindSequence({"Up","Up","Down","Down"}, &GodMode);
Console::Register("give", &GiveItem);
Console::Register("teleport", &Teleport);
}
#endifThe same idea in Unreal is UE_BUILD_SHIPPING, in Unity it is a scripting define stripped for the release player. The point is the linker drops the code. A runtime boolean such as bool cheatsEnabled = false is not enough, because the code, the command names and the strings are still in the binary and a memory patch or a config edit can flip the boolean.
How I test the shipped build
I run the test on the exact artefact that goes to the store, after symbols are stripped.
- Search the binary and its data files for cheat strings and command names:
strings Game.exe | grep -i -E "godmode|give|teleport|noclip". In a clean shipping build that returns nothing. I also check for debug symbols withdumpbin /symbolsornm, and for leftover console commands by opening the console in game and typinghelp. - Try the known sequences and commands from the debug build. Every one should do nothing, not even a partial response.
- Check the side doors cheats usually travel with: a debug config file the game reads from the install folder, an HTTP or local socket endpoint for remote control, and save files that accept a
cheat_usedflag. A cheat removed from the input code but still honoured when read from a save is still live.
| Leftover | What a player does with it | What it breaks |
|---|---|---|
| God mode / infinite health | Enter the sequence, finish any boss | Leaderboards, achievements, speedrun times |
give / spawn item | Spawn currency or rare drops | Economy, trading, save integrity |
teleport / noclip | Skip levels, leave the map | Progression gating, collision assumptions |
| Debug console | Call any registered command directly | All of the above, plus crash and save corruption commands |
| Debug flag in a config file | Edit one line in the shipped config | Same as the console, no patching needed |
A worked trace
In the debug build, pressing Up, Up, Down, Down sets player.invulnerable = true and prints God mode on to the console. In the shipping build I run the same sequence on the stripped binary. Expected result: no print, no state change, and the string God mode on does not appear in strings output. If the string is there, the code is there, and I treat the build as failed even if I cannot trigger it from the keyboard, because someone will find the trigger or patch the check.
Failure modes I have seen
The common one is a cheat guarded by #if !SHIPPING in one file and by a runtime flag in another, where the second file still registers the console command in shipping. The command then works even though the menu item is gone. The fix is one macro, one registration site, and the binary search above as a build step that fails the pipeline if a banned string appears.
The other is leaving the debug build's test account or test server address in the shipping client. That is not a cheat code, but it gives the same result: a hidden path into systems that were never meant to be reachable. Both get caught by the same rule. If it is not meant for a player, it is not in the shipping binary, and the shipping binary is what I test.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-95Your character jumps fine on flat ground but the jump is rejected on a 25-degree slope, and lowering the walkable-slope threshold makes it worse. Walk me through how you would diagnose it with ground-normal tests and fix it without letting the character jump off walls?
The 90-second answer
I would not start by tuning the threshold. I would log the three values that gate the jump on the exact frame the input is pressed: the ground normal returned by the ground probe, its dot product with world up, and the grounded flag the jump code actually reads. On a slope the usual failure is not a bad threshold. It is that the probe returns a normal from a different contact than the one the character is standing on, or the grounded flag is cleared by the slope projection before the jump check runs. Once I can see which of those three flips first, the fix is local.
Assume a capsule character, a sphere cast down from the capsule centre, and a walkable slope limit of 45 degrees. The test is dot(normal, up) >= cos(45°), which is >= 0.7071. At 25 degrees the dot is cos(25°) = 0.9063, so a jump rejected there is not explained by a 45 degree limit. Something else is feeding the check.
// C++17, checked against a capsule vs. static triangle world
struct GroundProbe {
bool hit;
Vector3 normal; // from the sphere cast, world space
float distance;
};
bool IsWalkable(const Vector3& n, float maxSlopeDeg) {
float minDot = std::cos(DegToRad(maxSlopeDeg));
return n.y >= minDot; // up is (0,1,0), so n.y is the dot
}
bool CanJump(const GroundProbe& g, float maxSlopeDeg) {
return g.hit && IsWalkable(g.normal, maxSlopeDeg);
}The diagnostic build logs one line per jump press, plus one line per physics step while grounded on the test ramp:
press t=12.431 hit=1 n=(0.000,0.906,0.423) dot=0.906 walkable=1 grounded=1 jump=1
press t=12.431 hit=1 n=(0.000,0.906,0.423) dot=0.906 walkable=1 grounded=0 jump=0The second line is the tell. Normal and threshold pass, grounded is false. That points at the ground probe missing on the slope, often because the cast starts inside the capsule on a slope and the engine reports no hit, or because the step-up code lifts the capsule and the probe distance is now larger than the probe length.
| Ramp angle | Expected dot | If jump fails, check first |
|---|---|---|
| 0° | 1.000 | Input buffering, jump velocity applied |
| 25° | 0.906 | Grounded flag, probe distance |
| 45° | 0.707 | Boundary case, normal averaging |
| 60° | 0.500 | Correctly rejected as wall-like |
How I reproduce it as a test, not a hunch
I build a straight ramp the character walks up at constant speed, with a jump press injected at fixed distances: 0, 10, 20 and 30 degrees, plus 44, 45 and 46 degrees for the boundary. Each run records the probe normal, dot, grounded flag and whether vertical velocity changed on the press frame. A pass is not "it jumped". A pass is dot within 0.01 of the analytic value for that angle, grounded true on the press frame, and jump velocity applied that same frame. That catches the case where the character jumps a frame late from coyote time and looks fixed in manual play.
Two failure modes show up repeatedly. First, averaged normals. If the probe blends contacts from the ramp and a small ledge or step at its base, the blended normal can tilt past the limit even though the contact under the feet is fine. I test this by logging every contact normal, not just the blended one, and by running the ramp with and without the ledge geometry. Second, the probe origin. On a slope, a cast from the capsule centre with a short length can start below the surface on the downhill side. Lengthening the probe by the capsule radius plus a small skin width, and casting from the capsule base instead of the centre, removes that without changing the threshold.
Fixing it without opening the wall exploit
If the log shows dot passing and grounded false, I fix the probe, not the threshold. If the log shows dot failing at 25 degrees, I look at the raw contact normals. A single noisy contact from a low tessellation ramp can spike the normal. I then use the normal of the contact closest to the capsule base, or the dominant contact by penetration depth, rather than an average of all contacts.
I keep the wall case separate. A wall at 80 degrees has dot 0.174, well below 0.707, so it stays rejected. I verify that with a wall jump test: press jump against a vertical wall while grounded on the floor at its base, and confirm the character does not gain upward velocity from the wall contact. If it does, the walkable check is being applied to the wrong contact, usually the floor contact while the wall contact is what the code reads.
The threshold itself only changes if the design limit changes. Moving from 45 to 50 degrees moves the cutoff dot from 0.7071 to 0.6428. I would make that change in one place, the maxSlopeDeg value, and rerun the boundary runs at 49, 50 and 51 degrees. Tuning it per ramp in level data is how the same jump starts working in one level and failing in the next.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-96Frame time rose 3 ms after a refactor and EnemyAI::Tick is up 2.8 ms in the profiler. How would you use before and after captures to confirm that scope caused it and rule out noise?
The 90-second answer
I would compare the same scene on both builds, then diff the timeline by scope. If one scope accounts for almost all of the 3 ms, I test that scope in isolation before changing code.
First I make the captures comparable. Same level, same seed, same scripted camera path, same enemy count, and a warmup of a few seconds before I start recording. I run each build three times and use the median frame time. A single run can pick up a shader compile, a streaming chunk or thermal throttling, and any of those can add a few milliseconds.
Then I align the captures on frame start and sort scopes by the change in time, not by total time. In this case the diff points at one place:
Hypothetical medians from three 600 frame runs, 16.6 ms budget at 60 fps:
| Scope | Before | After | Delta |
|---|---|---|---|
| GameThread total | 11.2 ms | 14.1 ms | +2.9 ms |
| EnemyAI::Tick | 1.8 ms | 4.6 ms | +2.8 ms |
| EnemyAI::FindTarget | 0.4 ms | 3.1 ms | +2.7 ms |
| Physics::Step | 3.0 ms | 3.0 ms | 0.0 ms |
| GPU frame | 9.8 ms | 9.9 ms | +0.1 ms |
FindTarget explains 2.7 ms of the 2.9 ms rise, while physics and GPU are flat. That narrows the search to the refactor inside that function. I then check call count against time per call. If FindTarget still runs once per enemy per frame but its cost per call rose from about 0.05 ms to 0.39 ms, the refactor made the work itself more expensive rather than calling it more often. Cache misses in that scope, if the profiler records them, usually rise with a change from a spatial lookup to a linear scan over 8,000 enemies.
Confirming the cause
I add a coarse marker around the changed code and recapture only to split the scope:
// C++ with Tracy, checked against Tracy 0.11
void EnemyAI::FindTarget()
{
ZoneScopedN("FindTarget");
ZoneScopedN("FindTarget::Scan");
for (const Enemy& e : enemies) { /* ... */ }
ZoneScopedN("FindTarget::PickBest");
// ...
}If Scan carries the delta and PickBest does not, I revert just the scan change on the after build and keep the rest of the refactor. A return to about 11.2 ms confirms that change. If the time stays high, the regression is an interaction with the rest of the refactor, such as changed memory layout, and I would diff allocation counts across the frame instead of trusting the scope name.
I also rerun the before build after the after build. If the extra 3 ms follows the build rather than the run order, run order artifacts are ruled out. If GPU time had risen by the same amount, I would check whether the frame was GPU bound, because extra CPU time hidden under GPU time may not change what the player sees.
The fix gets the same treatment. Restoring the spatial lookup should bring FindTarget back near 0.4 ms on the same scene and the same capture settings. If it does not, I trust the new capture over my reading of the first diff.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-97A reviewer flags a raw new in your bullet spawn code that runs every frame. How would you replace it with a fixed-size pool, and what should happen when the pool runs out?
The 90-second answer
I would accept the comment and replace the per-spawn new with a fixed-size pool allocated once at level load. The pool owns one contiguous array of bullets and a stack of free indices. Spawning pops an index, constructs the bullet in place, and returns a pointer into the array. Releasing destroys the bullet and pushes the index back. After construction there is no heap allocation in the spawn path, and the pointer stays valid until release because the array never moves.
When the pool runs out, spawn returns nullptr and the caller drops that spawn. For bullets that is a deliberate gameplay choice. A dropped bullet is invisible for one frame. Recycling the oldest bullet instead would keep the count up but would silently teleport a live bullet, which is harder to notice in testing.
The mechanism
// C++17, main thread only. Capacity is set from the design limit.
struct Bullet {
Vec3 pos;
Vec3 vel;
float life;
};
class BulletPool {
public:
explicit BulletPool(size_t capacity)
: storage_(capacity), alive_(capacity, 0) {
for (size_t i = capacity; i-- > 0; ) free_.push_back(i);
}
Bullet* spawn(const Vec3& pos, const Vec3& vel) {
if (free_.empty()) {
++dropped_;
return nullptr;
}
size_t i = free_.back();
free_.pop_back();
Bullet* b = new (&storage_[i]) Bullet{pos, vel, 2.0f};
alive_[i] = 1;
return b;
}
void release(Bullet* b) {
size_t i = static_cast<size_t>(b - storage_.data());
if (!alive_[i]) return; // double release: assert in debug builds
b->~Bullet();
alive_[i] = 0;
free_.push_back(i);
}
size_t dropped() const { return dropped_; }
private:
std::vector<Bullet> storage_;
std::vector<size_t> free_;
std::vector<char> alive_;
size_t dropped_ = 0;
};storage_ is the only heap allocation, made in the constructor. free_ holds indices, not pointers, so iteration over the array stays contiguous. Placement new runs the constructor without allocating. The destructor call in release matters if Bullet later gains a member that owns something, such as a string or a handle.
Worked trace
Capacity 3, so free_ starts as [2, 1, 0] with the back at the right.
| Call | Result | free_ after |
|---|---|---|
| --- | --- | --- |
spawn(A) | bullet at index 0 | [2, 1] |
spawn(B) | bullet at index 1 | [2] |
release(A) | index 0 destroyed, pushed back | [2, 0] |
spawn(C) | bullet at index 0 again | [2] |
spawn(D) | bullet at index 2 | [] |
spawn(E) | nullptr, dropped_ becomes 1 | [] |
That last row is the exhaustion policy in action. The caller checks the return value:
if (Bullet* b = pool.spawn(pos, vel)) {
b->pos = pos;
}Why this beats new here, with figures
Hypothetical but concrete: a burst weapon spawns 300 bullets per frame at 60 fps, which is 18,000 allocations per second. Each new and delete pair touches the allocator, may take a lock, and scatters the objects across the heap. Even at 200 ns per pair, that is 3.6 ms of allocator work per second, delivered unevenly, so one frame can absorb a spike while the next absorbs none. The pool turns the same work into a stack pop, a placement construction, and a few writes, with no allocator call after startup. The frame cost becomes flat, which is what the budget needs.
Sizing the pool is a design input, not a guess. If the design limit is 2,048 live bullets, the pool is 2,048. I would also expose dropped() to a debug counter. If dropped_ climbs during playtesting, the limit is wrong or the spawn rate is wrong, and that is a design conversation with evidence attached.
Failure modes to name in the reply
Exhaustion is handled by the drop counter above. A stale pointer is the other one. After release, slot 0 can hold a new bullet, so a pointer saved from the old bullet now points at live data with a different identity. Inside the spawn system I avoid saving bullet pointers across frames. If a system must hold one, it should hold a slot index plus a generation number that increments on each reuse, and check the generation before use. For this change I would keep the scope small: pool, drop policy, drop counter, and a profiler trace showing zero allocations in the spawn function.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-98How would you use profiler data to show a designer that a feature breaks the 16.6 ms frame budget at 60 fps?
The 90-second answer
60 fps gives you 16.6 ms per frame. 1000 divided by 60 is 16.66, so anything that pushes the frame past that line misses the target, no matter how good it looks in a screenshot.
I used that line to settle a disagreement with a designer over per-torch dynamic shadows in a dungeon level. He wanted every torch to cast a shadow. I said the level would not hold 60 fps. We stopped debating and captured the same scene on target hardware with the feature off and on.
With shadows off, the profiler showed 7.8 ms on the CPU main thread and 14.9 ms on the GPU. With 180 shadow-casting point lights at a 2048 map, GPU time rose to 31.4 ms and the shadow pass alone issued about 2,400 draw calls. That is a second render of the level depth, repeated for each light. The frame was over budget by almost double, and the capture proved it in one screen.
We shipped a compromise. One shadow light followed the player, the other torches stayed unshadowed and relied on baked probes, and that one map dropped to 1024. GPU time came back to 15.1 ms and p95 frame time was 16.4 ms. He kept shadows where the player looks. We kept 60 fps.
The trace I showed him
I captured the worst camera angle in the room, with the particle effects running, because an average frame hides the spike that players feel.
| Capture | CPU main thread | GPU frame | Shadow draw calls | p95 frame |
|---|---|---|---|---|
| Shadows off | 7.8 ms | 14.9 ms | 0 | 16.1 ms |
| 180 lights, 2048 map | 8.1 ms | 31.4 ms | 2,400 | 33.0 ms |
| Compromise build | 7.9 ms | 15.1 ms | 310 | 16.4 ms |
Two checks mattered before I showed the table. First, CPU was flat at about 8 ms in all three runs, so this was GPU bound and trimming code would not fix it. Second, I used the same build, same scene and same camera, so the only variable was the shadow setting. That made the before and after comparison hard to argue with.
What happened next
I gave him three options with the cost attached. His version at 31.4 ms meant 30 fps or a resolution cut. The compromise at 15.1 ms kept the look near the player. A blob shadow under each torch at 14.6 ms was cheaper again but lost the soft directional shape he wanted. He picked the compromise after seeing both captures in the real level.
I also added a load-time warning when a zone contains more than 8 shadow-casting lights, with the zone name in the log. That stopped the same argument recurring in the next level.
The point I took from it: bring the 16.6 ms line and a capture that crosses it. A designer can defend a visual choice, but a frame at 31 ms on target hardware is a fact both sides can work from.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-99Tell me about a time you integrated a teammate's breaking change that broke the build, and how you used tests and a merge plan to recover without losing their work or your team's deadline?
The 90-second answer
Two weeks before our content lock, our physics owner landed a branch that replaced Entity* with a generational Handle and moved components from a vector<Component*> per entity to a sparse set keyed by handle. It was the right change. It also broke 43 files, every script binding, and the save loader in one commit. My job was not to revert it and not to let the team absorb it as a week of red builds. I treated it as an integration project with a contract, a shim, and a merge window.
First I froze the blast radius. I branched from the last green main, cherry-picked her commit onto integration/handle, and ran the build to get the exact failure list instead of arguing from the diff. That gave me 43 compile errors in 6 clusters: core ECS, physics callbacks, Lua bindings, save/load, editor tools, and tests. I told the team main stayed green, no one merged to main until the integration branch passed the full suite, and Maya and I paired on the clusters she owned while I took bindings and save/load.
Second I wrote the contract test before fixing call sites. The old code assumed a raw pointer stayed valid for the lifetime of a frame and that a recycled entity slot meant the same object. The new handle breaks both assumptions on purpose. If I had just fixed compile errors, we would have shipped use-after-recycle bugs that only showed up in a long play session.
// Checked against our C++17 ECS, integration/handle branch
TEST(HandleContract, RecycledSlotDoesNotAliasOldEntity) {
World w;
Handle old = w.spawn<Health>(100);
w.destroy(old);
Handle fresh = w.spawn<Health>(50); // reuses slot 0
EXPECT_EQ(old.index, fresh.index); // same slot, by design
EXPECT_NE(old.generation, fresh.generation); // generation distinguishes them
EXPECT_FALSE(w.alive(old));
EXPECT_TRUE(w.alive(fresh));
EXPECT_EQ(w.get<Health>(fresh).hp, 50);
// Old handle must fail loudly, not return the new entity's health
EXPECT_THROW(w.get<Health>(old), StaleHandle);
}That test failed on the first integration build because the Lua binding cached the old raw pointer. It passed after we changed bindings to store the handle and resolve it per call. The test is the artefact I would point an interviewer to. It captures the semantic break, not just the syntax break.
Third I used a temporary adapter where it bought time, and deleted it where it hid bugs. For save/load I kept a v1 reader that translated old integer IDs to handles on load, with a migration counter logged at startup. For physics callbacks, which fire during a step and can destroy entities, I refused an adapter that cached pointers. Those call sites had to resolve the handle inside the callback and check alive() before touching the component. The rule I used: an adapter is fine for data at a boundary, dangerous for lifetime inside a frame.
Merge plan and trace
| Step | Owner | Gate to proceed |
|---|---|---|
| Core ECS + contract test | Maya | HandleContract suite green, no raw Entity* in core |
| Physics callbacks | Maya + me | 10 minute soak, zero StaleHandle in log, no crash in replay |
| Lua bindings | Me | Script smoke test spawns, kills, respawns 1,000 entities |
| Save/load migration | Me | v1 save from last shipped build loads, v2 save round-trips |
| Editor tools | Level team | Open, save, reload the test level with 2,000 placed entities |
| Merge to main | Me | Full CI green twice in a row, then merge in the morning, not Friday night |
The trace that mattered was not the compile list. It was this sequence on the integration branch: build green, contract test red on bindings, fix bindings, contract test green, soak test produced 17 StaleHandle throws from a particle system that stored handles across frames without checking. Those were real bugs the old pointer code had hidden by returning freed memory. We fixed the particle system to drop stale handles instead of throwing in shipping code, and the soak went clean. Only then did we merge.
Result and what I would do differently
We merged on the Wednesday, three days after the break, with main green throughout and no revert. The cost was one day of feature work on the integration branch, which we had already scheduled as a buffer. The gain was that the generational handle shipped before content lock, so designers built levels against the final API instead of against a shim we would later remove.
I would not repeat one mistake. I let the branch sit for four days before integrating because the change looked self-contained in review. Breaking changes to identity, ownership, or save format need an integration branch and a contract test in the same pull request, not after it lands. If a teammate proposes that kind of change now, I ask for the failing test that proves the old assumption is gone, and I book the merge window before the code is written.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-100Your playable build is 3 weeks late, the frame is 23ms against a 16.6ms budget, and you must ship in 2 weeks: walk me through how you prioritise and cut scope to prove the cut build fits?
The 90-second answer
I was gameplay programmer on a Unity arena game, team of five, milestone in 2 weeks instead of 5. At that point the build ran at 23 ms per frame against a 16.6 ms budget for 60 fps, and the match could not be finished because win, lose and restart were stubs. I put the remaining work in a table with days to finish and frame cost, kept only what made a match playable end to end, and cut enough frame cost to get under budget with headroom. We shipped in the 2 weeks with timer, two enemy types, spawning, pause and restart working, and deferred the boss, daily mode and leaderboard. Testers finished a match in 4 of 5 sessions.
Situation
Movement and spawning worked in isolation. The milestone definition was written down: start, fight waves, win or lose, restart, no console errors, 60 fps on the target laptop. Profiler on that laptop, 60 second run, median frame: update 9 ms, physics 6 ms, render 8 ms. Total 23 ms. That is 6.4 ms over budget before any new feature. The producer forecast was 5 weeks to finish everything. We had 2.
Action: prioritise by loop first, then by frame cost
I listed each item with the producer and lead. The rule was simple. If a tester cannot finish a match without it, it stays. If it does not affect finishing a match, it goes unless it is cheap in both days and milliseconds.
| Feature | Days left | Frame cost | Decision |
|---|---|---|---|
| Match timer, win/lose, restart | 4 | 0.3 ms | Keep, do first |
| Wave spawner, 2 enemy types | 3 | 1.0 ms | Keep |
| Pause, minimal | 1 | 0.1 ms | Keep |
| Hardcoded tutorial prompts, 3 lines | 1 | 0 ms | Keep |
| Third enemy type | 5 | 1.2 ms | Defer |
| Boss with new AI pass and particles | 7 | 3.5 ms | Defer |
| Daily challenge mode | 5 | 0.5 ms | Defer |
| Leaderboard upload | 6 | 0.2 ms | Cut for this milestone |
| Cosmetic skins | 4 | 0.4 ms | Cut |
Keeping the first four rows costs 9 days of work spread across the team and adds 1.4 ms. That alone does not fix the frame. So the second half was optimisation of what we already had, not new content. Update at 9 ms was the largest block. Profiling showed enemy separation running every frame for 300 enemies, O(n squared) checks, at 5.5 ms. Moving it to a spatial hash and running it every second frame cut it to 1.8 ms. Physics at 6 ms included a particle collision pass we could run at half rate for background particles, saving 1.5 ms. Render at 8 ms dropped 1.2 ms when we disabled per enemy shadow casting for small enemies.
Worked total after cuts and optimisation: update 9 minus 3.7 plus 1.4 for kept features equals 6.7 ms, physics 6 minus 1.5 equals 4.5 ms, render 8 minus 1.2 equals 6.8 ms. Sum is 18.0 ms. Still over. That forced one more decision. We reduced particle count in the explosion effect from 2,000 to 900 and capped active enemies at 220 instead of 300. That saved another 1.6 ms in update and physics combined. Final median was 16.4 ms, with 95th percentile at 16.6 ms in the 60 second run. Tight, but inside budget, and we had a known lever left if it regressed.
The alternative I rejected was keeping the boss and optimising harder to fit it. Boss alone added 3.5 ms and 7 days. Even with the same optimisations we would have landed near 19.9 ms and needed a second optimisation pass we had no time to test. Cutting content was the safer trade because frame cost is measurable on day one, while optimisation gains are not guaranteed.
Verification
From that day we used a daily playable rule. At 17:00 a person who had not written that day's code had to start a match, play 2 minutes, trigger win and lose, and restart. Checklist: timer counts, restart resets enemy count to zero, no console errors, and the 60 second profiler run stays under 16.6 ms at the 95th percentile. Failures were reverted that evening. On day 3 restart left 40 enemies alive. We caught it because the checklist required a zero count, not because a tester reported it.
Result
We shipped on the Friday. The deferred features returned next milestone. The leaderboard was cut rather than deferred because it needed server auth and moderation, and a half finished upload path would have produced silent failures in the field. I kept a minimal best time save with a version field, half a day of work, because losing progress between tester sessions looks like a crash and would have been hard to fix in the final week.
What I would do earlier next time is run this table at week 4. We spent a week polishing the third enemy before admitting it was at risk. Once the forecast slips by more than 20 percent, the cut list needs to be agreed while people can still be reassigned, not in the final 2 weeks.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.