Short on time? Game engine technology turns maths into motion: physics keeps objects believable, mathematics moves and rotates everything, game theory shapes how opponents and difficulty behave, and animation gives characters life. This guide walks through each area with real source code from id Software, the Bullet Physics SDK and short examples of our own, plus what studios such as Rockstar, Naughty Dog, Valve, Epic and Unity have published about their tools.
Every hit game hides a small pile of ideas that did the hard work. DOOM needed fast maths on slow processors. Quake III Arena needed a quicker way to find a square root. Grand Theft Auto and Red Dead Redemption needed an engine that could run a living world. The Last of Us needed an engine that could hold 60 frames per second on a console. Left 4 Dead needed an enemy director that kept every playthrough fresh.
This guide follows those ideas through four areas: physics, mathematics, game theory and animation. It shows code where code explains best, and it points to the original sources so you can read further. It suits developers, technical artists, producers and anyone planning a game of any size.
Key takeaways
- Every engine repeats one loop each frame, and every system inside it shares a budget of about 16.6 milliseconds at 60 frames per second.
- Physics runs on a fixed time step so results stay the same at any frame rate.
- A small set of maths tools does most of the work: vectors, matrices, quaternions, fixed-point numbers and clever approximations.
- Game theory appears in search, difficulty, pacing and economies, from minimax to Valve’s AI Director.
- Animation blends authored motion with physics, and capture pipelines feed both.
- Real source code from id Software and Bullet is open for study, and the licences tell you how to use it.
A short history in source code
DOOM: fast maths on slow machines
id Software released the DOOM source code in December 1997. The release note, written by John Carmack, says the code was released for non-profit use, that it needed Linux to build, and it discusses design choices in hindsight, including the binary space partition (BSP) tree used to draw the world front to back. The DOOM repository lists the GPL-2.0 licence.
DOOM’s code uses fixed-point numbers: whole numbers that stand for fractions. Here is its multiply function from m_fixed.c, Copyright id Software.
fixed_t
FixedMul
( fixed_t a,
fixed_t b )
{
return ((long long) a * (long long) b) >> FRACBITS;
} The two values are multiplied as larger integers, then shifted right by FRACBITS bits to bring the result back to the same scale. No floating point is needed, and the result is exact and fast. Fixed-point maths still appears in embedded systems, audio code and networked games, where every machine must calculate exactly the same answer.
Quake III Arena: a famous approximation
Lighting and physics need many inverse square roots, which means calculating one divided by the square root of a number. Quake III Arena’s source, released under the GPL, contains a well-known function for this in code/game/q_math.c, Copyright id Software. One comment is omitted here.
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
return y;
} It reads the bits of a floating point number as an integer, uses a magic constant to make a first guess, and then improves the guess with one step of Newton’s method. The result is close enough for lighting, and it costs far less than a full calculation. The pointer tricks in this code are undefined behaviour in modern C++, where std::bit_cast or memcpy is the safe way to reinterpret bits, and today’s processors also have a built-in fast reciprocal square root instruction. The lesson holds: knowing the maths lets you trade a little accuracy for a lot of speed.
What studios have said about their technology
Studios share engine details through release notes, talks and documentation. These first-party sources are the most reliable place to learn.
Rockstar Games. A Rockstar announcement published on Take-Two’s investor site on December 1, 2009 says Red Dead Redemption is built on the internally developed Rockstar Advanced Game Engine (RAGE) and NaturalMotion’s Euphoria physics featured in Grand Theft Auto IV and Midnight Club: Los Angeles. So a proprietary engine drove open worlds, with a partner’s physics-driven character technology.
Naughty Dog. The studio behind Uncharted and The Last of Us lists its 2015 Game Developers Conference sessions on its blog. One was a talk by lead programmer Christian Gyrling on parallelising the engine with fibers. The listing says it covers the engine changes needed to run The Last of Us Remastered at 60 frames per second on PlayStation 4, including a fiber-based job system, a frame-centric engine design, memory allocation patterns and strategies for handling locks. Another session, by the motion capture pipeline technical director, covered capturing The Last of Us.
Valve. Michael Booth’s slides on the AI systems of Left 4 Dead describe finding paths with A-star over a navigation mesh, then following them with local obstacle avoidance so movement looks fluid. They also describe the AI Director, which fills the world with enemies and items using what Valve calls structured unpredictability.
Epic Games. Epic’s documentation describes Chaos physics for rigid bodies, real-time destruction, vehicles with any number of wheels, cloth and ragdolls.
Unity. Unity’s physics overview says its default built-in 3D physics system is an integration of the Nvidia PhysX engine, and its Time settings describe a fixed timestep as a frame-rate-independent interval for physics calculations.
Hardware makers. Microsoft’s Xbox Series X page lists an eight-core Zen 2 processor and a 12 teraflop graphics processor with 16 GB of memory. Sony’s PlayStation 5 page describes an ultra-high-speed solid-state drive, ray tracing and 3D audio. Fast storage and many cores shape how engines stream worlds and run systems in parallel.
Game engine technology: the loop every frame
Whatever the studio, game engine technology follows one rhythm. Here is a simplified main loop:
while (running) {
read_input();
update_world(dt); // traffic, weather, scripts
step_physics(dt); // move and collide objects
update_animation(dt); // pose every visible character
run_ai(dt); // decide what characters do
stream_world(); // load and unload areas
render_frame(); // draw the scene
mix_audio();
} At 60 frames per second the whole loop must finish in about 16.6 milliseconds. At 30 it has about 33.3. Teams give each system a slice and protect the total. See game rendering basics for the drawing side.
Jobs and parallel work
Modern consoles have many cores, so engines split work into small jobs that run in parallel. Naughty Dog’s talk, as listed on its blog, centres on a fiber-based job system for this reason. Here is the same idea in plain C++, splitting a crowd update into groups of 64 characters:
std::vector<std::future<void>> jobs;
for (size_t start = 0; start < crowd.size(); start += 64) {
size_t end = std::min(start + 64, crowd.size());
jobs.push_back(std::async(std::launch::async, update_group, start, end));
}
for (auto& job : jobs) job.get(); // wait for every job before drawing Production engines use custom schedulers that avoid the cost of operating system threads, and the principle is the same: cut the frame into pieces, run the pieces side by side and wait only when you must.
Build or license
Teams can build an engine, as Rockstar and Naughty Dog do, or license one such as Unreal or Unity. Building gives control and demands tools, training and upkeep. Licensing gives speed and carries the engine’s limits. See game engines compared.
Physics in game engine technology
Fixed time steps
Physics must give the same result at any frame rate. The standard answer is a fixed time step. Unity’s documentation describes it as an interval that dictates when physics calculations are performed, and its Maximum Allowed Timestep caps the worst case when the frame rate is low.
The Bullet Physics SDK, an open-source library whose repository states a permissive zlib licence, shows the technique clearly. This condensed and simplified excerpt comes from btDiscreteDynamicsWorld::stepSimulation in src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.cpp, Copyright Erwin Coumans, zlib licence.
// fixed timestep with interpolation
m_fixedTimeStep = fixedTimeStep;
m_localTime += timeStep;
if (m_localTime >= fixedTimeStep)
{
numSimulationSubSteps = int(m_localTime / fixedTimeStep);
m_localTime -= numSimulationSubSteps * fixedTimeStep;
}
// clamp the number of substeps, to prevent simulation grinding spiralling down to a halt
int clampedSimulationSteps = (numSimulationSubSteps > maxSubSteps) ? maxSubSteps : numSimulationSubSteps;
applyGravity();
for (int i = 0; i < clampedSimulationSteps; i++)
{
internalSingleStepSimulation(fixedTimeStep);
}
synchronizeMotionStates(); What happens, step by step:
- Real elapsed time is added to an accumulator.
- The code finds how many fixed slices fit, and keeps the remainder.
- It caps the number of slices, so one slow frame cannot start a spiral of ever longer catch-up work.
- It applies gravity, runs one step per slice and updates what the player sees.
Integration
Each slice moves objects with a small update. This example uses semi-implicit Euler, which updates velocity first:
velocity += acceleration * dt;
position += velocity * dt; The order matters. Updating velocity before position keeps simulations more stable than the naive order, and it is the basis of many game physics engines.
Collisions
Engines test cheap shapes first. An axis-aligned bounding box overlap test is only six comparisons:
bool overlaps(const Box& a, const Box& b) {
return a.min.x <= b.max.x && a.max.x >= b.min.x &&
a.min.y <= b.max.y && a.max.y >= b.min.y &&
a.min.z <= b.max.z && a.max.z >= b.min.z;
} A broad phase uses structures such as grids and trees to find which pairs might touch. A narrow phase then tests those pairs in detail. Objects at rest go to sleep and cost nothing until something wakes them. Epic’s Chaos documentation lists collision responses, constraints, damping and friction for rigid bodies, destruction through fracture, and vehicles that support any number of wheels. See game physics for tunnelling and stability.
Tuning for feel
Real-world values often feel wrong in a game. Designers raise gravity for snappier jumps, add grip so cars corner well and forgive timing at ledges. Physics serves play, so tuning is part of the engineering.
Mathematics behind every frame
Vectors and dot products
Vectors hold positions, directions and speeds. The dot product tells you how much two directions agree:
float dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; } If a guard’s facing direction and the direction to the player have a dot product above a chosen value, the player is inside the guard’s view cone. The same line of maths drives lighting, since surfaces facing a light have a larger dot product.
Quaternions and smooth rotation
Rotations are stored as quaternions, which avoid gimbal lock and blend smoothly. Bullet’s btQuaternion::slerp, in src/LinearMath/btQuaternion.h (zlib licence, Copyright Erwin Coumans), performs spherical linear interpolation. This is the main branch:
const btScalar magnitude = btSqrt(length2() * q.length2());
btAssert(magnitude > btScalar(0));
const btScalar product = dot(q) / magnitude;
const btScalar absproduct = btFabs(product);
if (absproduct < btScalar(1.0 - SIMD_EPSILON))
{
// Take care of long angle case see http://en.wikipedia.org/wiki/Slerp
const btScalar theta = btAcos(absproduct);
const btScalar d = btSin(theta);
btAssert(d > btScalar(0));
const btScalar sign = (product < 0) ? btScalar(-1) : btScalar(1);
const btScalar s0 = btSin((btScalar(1.0) - t) * theta) / d;
const btScalar s1 = btSin(sign * t * theta) / d;
return btQuaternion(
(m_floats[0] * s0 + q.x() * s1),
(m_floats[1] * s0 + q.y() * s1),
(m_floats[2] * s0 + q.z() * s1),
(m_floats[3] * s0 + q.w() * s1));
} Here t runs from 0 (the first rotation) to 1 (the second). The angle theta comes from the dot product, and the two sine weights s0 and s1 blend the rotations along the shortest path. When the rotations are nearly equal, the code takes a simpler path, because dividing by a tiny sine would be unstable.
Precision in big worlds
Floating point numbers lose precision far from the origin, so objects far from the centre of a huge map can jitter. Open-world engines handle it by shifting the origin as the player moves, or by splitting the world into regions that each have their own local origin. DOOM’s fixed-point numbers, shown earlier, solve a related problem by making precision the same everywhere.
Randomness with a seed
Games use pseudo-random numbers that start from a seed, so the same seed gives the same results. That makes variety and repeatable tests possible together. See procedural generation in games.
Game theory in games
Game theory studies decisions when other agents also decide. Games use it everywhere.
Adversarial search
Minimax searches a tree of moves, assuming each side picks its best option. This example scores tic-tac-toe, where X tries to maximise the score and O tries to minimise it:
def minimax(board, player):
winner = check_winner(board)
if winner == "X": return 1
if winner == "O": return -1
if is_full(board): return 0
scores = []
for move in empty_squares(board):
board[move] = player
scores.append(minimax(board, "O" if player == "X" else "X"))
board[move] = None
return max(scores) if player == "X" else min(scores) Chess programs and many strategy games use deeper versions with pruning. Google DeepMind’s AlphaGo page describes a system that combines deep neural networks with advanced search algorithms, learned first from expert games and then from reinforcement learning through self-play, and notes that it beat Lee Sedol 4-1 in March 2016. Search plus learned judgement is now a standard pattern in game AI research.
Pathfinding as a search problem
Valve’s slides describe A-star over a navigation mesh. Here is A-star on a grid with a Manhattan distance guess:
import heapq
def a_star(grid, start, goal):
def h(p): return abs(p[0] - goal[0]) + abs(p[1] - goal[1])
open_set = [(h(start), 0, start)]
came_from, cost = {}, {start: 0}
while open_set:
_, g, cur = heapq.heappop(open_set)
if cur == goal: break
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nxt = (cur[0] + dx, cur[1] + dy)
if not grid.walkable(nxt): continue
new_cost = g + 1
if new_cost < cost.get(nxt, 1e9):
cost[nxt] = new_cost
came_from[nxt] = cur
heapq.heappush(open_set, (new_cost + h(nxt), new_cost, nxt))
return came_from The guess steers the search toward the goal, and a path that never overestimates keeps the result shortest. See game AI basics.
Designed unpredictability
Valve’s slides explain why static enemy placement hurts replay: players memorise it. The AI Director instead mixes several population rules, each with designer-set randomness. One example in the slides is mobs that spawn at a randomised interval between 90 and 180 seconds. In code, the idea is one line:
next_mob_time = now + random.uniform(90, 180) Wanderers appear often, mobs at a medium rate, bosses rarely. The result is structured unpredictability: players cannot memorise it, and designers can still tune it. The same thinking shapes loot tables, in-game economies and matchmaking. See game economy design.
Animation: from skeletons to physics
Skeletons and blending
A hidden skeleton of joints moves, and the mesh follows. Clips such as walk and run are blended by speed and direction. At its simplest, blending is a weighted mix of two poses:
Vec3 lerp(Vec3 a, Vec3 b, float t) { return a + (b - a) * t; }
// positions use lerp, rotations use the slerp shown earlier State machines and graphs decide which clip plays and how to move between clips. Inverse kinematics solves joint angles so a foot meets uneven ground or a hand meets a handle.
Capture and authored motion
Realistic motion often starts with performance capture. Naughty Dog’s 2015 listing includes a session on capturing The Last of Us by its motion capture pipeline technical director, and an animation panel with one of its animators. Capture data then goes through cleaning, retargeting to the game skeleton and blending in the engine. See game art pipelines.
Physics-driven characters
Rockstar’s release names NaturalMotion’s Euphoria as physics technology in its games. Epic’s documentation describes ragdolls as rigid bodies attached to a skeletal mesh that simulate in real time, commonly to animate falling humanoids. Games usually mix authored animation with ragdoll physics, and switch between them when a character is hit, so a stumble or a fall differs from one moment to the next.
Level of detail
Crowds use cheaper skeletons and update less often at a distance. Without that saving, a busy street would use the whole frame budget on pedestrians.
A worked example: one frame in a car chase
This example is illustrative, with teaching values for a 30 frames per second target.
The frame lasts 33.3 milliseconds. A team might split it like this:
- Game logic and artificial intelligence: 5 ms for traffic, police and pedestrians.
- Physics: 5 ms for the player car, nearby cars, debris and characters.
- Animation: 4 ms, with cheap updates for the crowd.
- Streaming and audio: 4 ms.
- Rendering preparation and drawing: 15 ms on the processor and graphics card, overlapping with the work above.
A crash adds debris, and physics rises to 9 ms. The team can reduce the debris count, put far objects to sleep or move work to another core. They change one thing, measure and repeat. See PC game optimisation for the same method on other hardware.
Lessons for studios of every size
- Solo developer or small team: pick an engine with solid physics and animation tools, set a frame budget on day one, use a fixed time step and test on the weakest device early.
- Mid-size studio: add a technical artist and a gameplay engineer who own the budget, set rules for assets, automate performance captures and write tests for maths and physics code.
- Large studio: treat the engine as a product, with tools, documentation, profiling dashboards, a job system and a certification plan for each platform. See console game development.
Whatever the size, test the feel as well as the numbers. See game testing and QA.
Licences and rights
Open-source code comes with terms. The zlib licence used by Bullet asks you to keep the notice and not claim you wrote the original software. The GPL used for the released id Software code asks that derived work stays under the same licence. Keep notices, check each licence before reuse and write your own code when you need a different licence. Game names and trademarks belong to their owners.
Games ship worldwide, and age ratings, consumer law, privacy rules and platform requirements vary by country and console. See game localisation.
Common mistakes
- Variable time steps in physics.
- Copying real-world physics numbers without tuning for fun.
- Using floating point everywhere without thinking about precision.
- Letting physics, animation and artificial intelligence each grow with no shared budget.
- Static enemy placement that players memorise.
- Reusing open-source code without checking the licence.
- Testing only on strong hardware.
A starting plan
- Set a frame budget for each target platform, and share it with every team.
- Prototype the systems that define your game’s feel: movement, physics and animation.
- Use a fixed time step, and test odd frame rates.
- Write small tests for maths code, such as quaternion blending and collision checks.
- Profile early and often, on real devices.
- Review your game engine technology choices every milestone: what must run every frame, what can wait and what can run in parallel.
How SoftSapien supports game engineering
SoftSapien’s game developers help studios choose engines, build and tune physics and character systems, write and review gameplay and maths code, set up animation and art pipelines, profile performance and prepare builds for mobile, PC and console release. Our teams also run QA and compatibility testing, so the feel you design is the feel players get. See our game development and QA and testing services.
To talk through your game, use the contact page to chat with our team, send a message or schedule a free consultation call.
Frequently asked questions
What is game engine technology?
The software and maths that run a game every frame: input, simulation, physics, animation, artificial intelligence, streaming, rendering and audio, all sharing a budget of about 16.6 milliseconds at 60 frames per second.
Which maths do game developers use most?
Vectors for positions and directions, matrices for moving and turning, quaternions for smooth rotation, interpolation for blending, fixed-point or carefully handled floating point numbers, and spatial structures such as grids and trees for fast lookups.
Why do games use a fixed time step for physics?
Physics advances in equal slices so results do not change with frame rate, and a cap on slices stops a slow frame from spiralling out of control.
How is game theory used in games?
In adversarial search such as minimax, in AI that balances difficulty and pacing, and in designed randomness such as Valve AI Director for Left 4 Dead.
Can SoftSapien help with game engineering?
Yes, from engine choice to release. Contact SoftSapien through the contact page to chat with our team, send a message or schedule a free consultation call.