Collision System: User Guide
Version 1.0 (Engine System final write-up, November 2026). Benjamin Yang. Questions are welcome on Slack or by email, and I'm happy to help you get it into your game.
The Collision library gives your game objects shapes that know about each other:
- Colliders: spheres and axis-aligned boxes, described in small Lua files and attached to your objects' rigid bodies.
- Layers: you name the kinds of things in your game (
"world","player","enemy", ...) and say which of them touch each other. - Solid response: walls stop things and floors hold them up. A moving collider that runs into something solid is pushed back out, and the part of its velocity that points into the surface is removed.
- Triggers: colliders that report overlaps but never push anything (pickups, checkpoints, damage zones, the goal).
- Events:
OnEnter,OnStayandOnExitfunctions on each collider, with the other collider, the contact normal and how deep they overlapped. - Raycasts: "what is the first thing in this direction, and how far away is it?" (ground checks, line of sight, shooting, AI that looks ahead).
It is not a physics engine. Nothing rotates, there is no mass, friction or bounciness, and gravity is up to you (set your rigid body's acceleration). You move your objects the way you always have, and the collision system keeps them out of each other.
It only uses engine code that we all got in Assignment 01 (Asserts, Logging, Math, Physics, Platform, Results, ScopeGuard, Windows, Lua and the AssetBuildLibrary), so it should drop into any of our solutions. Nothing in Graphics, in your meshes or in your effects has to change.
1. What is in the download
| Folder or file | What it is |
|---|---|
Engine/Collision/ | The run-time static library. Collision.h is the only header your game includes. This guide is in there too. |
Tools/ColliderBuilder/ | The builder that turns the human-readable .layers and .collider files into small binary files at build time (it is built like MeshBuilder). |
AssetBuildFunctions_Collision.lua | The two asset types to paste into your AssetBuildFunctions.lua (section 3). |
ExampleContent/ | An example layers file, six example collider files and the lines for AssetsToBuild.lua. |
Copying the two project folders into your solution only adds new folders. It doesn't replace any file that you already have.
2. Setting up your solution (once)
This takes about ten minutes. I tested these exact steps on a clean copy of my Assignment 08 solution, which had never had the collision system in it: all four configurations built with no errors and no warnings, and the game ran.
- Copy
Engine\Collisioninto your solution'sEnginefolder andTools\ColliderBuilderinto itsToolsfolder (next toMeshBuilder). - In Visual Studio's Solution Explorer, right-click the Engine solution folder > Add > Existing Project... and choose
Engine\Collision\Collision.vcxproj. Then right-click the Tools folder > Add > Existing Project... and chooseTools\ColliderBuilder\ColliderBuilder.vcxproj.- Collision references Asserts, Logging, Math, Physics, Platform, Results and Windows, which you already have.
- ColliderBuilder references Asserts, Platform, Windows, LuaLib and AssetBuildLibrary, the same as MeshBuilder.
- Both use
EngineDefaults.propslike every other project, so they build for x64 (Direct3D) and x86 (OpenGL) in Debug and Release, andColliderBuilder.exeends up next toMeshBuilder.exe.
- Right-click your game project (MyGame) > Add > Reference... and tick Collision.
- Right-click BuildMyGameAssets > Build Dependencies > Project Dependencies... and tick ColliderBuilder (the same way it depends on MeshBuilder), so that the builder is always built before your assets.
- Paste the asset types into
Tools\AssetBuildLibrary\AssetBuildFunctions.lua(section 3 says where). - Copy
ExampleContent\CollisionandExampleContent\CollidersintoMyGame_\Content(or write your own files, sections 4 and 5), and add the two tables fromExampleContent\AssetsToBuild_Collision.luatoMyGame_\Content\AssetsToBuild.lua(section 6). - Build the solution. Your game's
datafolder now hasCollision\game.binlayersand a.bincolliderfor every collider file. - Add the code to your game (section 7). When you run it, the first lines that the collision system writes to
eae6320.loglist your layers and what each of them touches:
Collision: initialized with 4 layers from "data/Collision/game.binlayers"
Collision: layer 0 "world" touches: player, enemy
Collision: layer 1 "player" touches: world, enemy, pickup
Collision: layer 2 "enemy" touches: world, player
Collision: layer 3 "pickup" touches: player
3. What to add to AssetBuildFunctions.lua
Paste the block below (it is also in AssetBuildFunctions_Collision.lua) right after your mesh asset type, before the line -- Local Function Definitions (the very end of the file works too). It calls NewAssetTypeInfo(), RegisterAssetToBeBuilt() and FindSourceContentAbsolutePathFromRelativePath(), which are local functions defined higher up in that file, so it has to come after them: pasted at the top of the file, the asset build fails with attempt to call a nil value (global 'NewAssetTypeInfo'). Nothing else in the file changes.
-- Collision Asset Types
------------------------
-- ColliderBuilder.exe builds both of the collision system's file types:
-- * the game's layers file (Collision/game.layers -> Collision/game.binlayers)
-- * collider files (e.g. Colliders/player.collider -> Colliders/player.bincollider)
-- A collider names its layer, and ColliderBuilder turns that name into the layer's index using the game's layers file,
-- so that file is always at the same path in the game's content directory
local collisionLayersRelativePath = "Collision/game.layers"
NewAssetTypeInfo( "collisionlayers",
{
ConvertSourceRelativePathToBuiltRelativePath = function( i_sourceRelativePath )
local relativeDirectory, file = i_sourceRelativePath:match( "(.-)([^/\\]+)$" )
local fileName = file:match( "([^%.]+)" )
return relativeDirectory .. fileName .. ".binlayers"
end,
GetBuilderRelativePath = function()
return "ColliderBuilder.exe"
end,
}
)
NewAssetTypeInfo( "colliders",
{
ConvertSourceRelativePathToBuiltRelativePath = function( i_sourceRelativePath )
local relativeDirectory, file = i_sourceRelativePath:match( "(.-)([^/\\]+)$" )
local fileName = file:match( "([^%.]+)" )
return relativeDirectory .. fileName .. ".bincollider"
end,
GetBuilderRelativePath = function()
return "ColliderBuilder.exe"
end,
RegisterReferencedAssets = function( i_sourceRelativePath )
-- Every collider uses the game's layers file (and the game loads it before any collider),
-- so it is built whenever any collider is
RegisterAssetToBeBuilt( collisionLayersRelativePath, "collisionlayers" )
end,
ShouldTargetBeBuilt = function( i_lastWriteTime_builtAsset )
-- A built collider stores the index of its layer,
-- so it has to be built again whenever the layers file changes
-- (if the layers file doesn't exist the collider's build reports that)
local path_layers = FindSourceContentAbsolutePathFromRelativePath( collisionLayersRelativePath )
if path_layers then
return GetLastWriteTime( path_layers ) > i_lastWriteTime_builtAsset
else
return true
end
end,
}
)
Because of ShouldTargetBeBuilt(), changing the layers file rebuilds every collider (a built collider stores the index of its layer, not its name). Because of RegisterReferencedAssets(), the layers file is built whenever any collider is, even if you forget to list it.
4. The layers file: Content/Collision/game.layers
Every game has exactly one layers file, and it must be at this path. It names the layers and says which pairs of layers touch each other:
return
{
layers =
{
"world", -- floors, walls, crates
"player",
"enemy",
"pickup",
},
-- Only these pairs touch (and push each other). Anything not listed passes through without any events.
interactions =
{
{ "player", "world" },
{ "player", "enemy" },
{ "player", "pickup" },
{ "enemy", "world" },
-- { "enemy", "enemy" }, -- a layer can be paired with itself
},
}
- 1 to 32 layers. Names must be unique and not empty.
- An interaction must name two layers from the list. The order inside a pair doesn't matter.
- Raycasts don't use the interactions. They choose layers with a layer mask instead (section 9).
- Making something not interact with something else is a one-line change here, with no code. For example, enemies don't collect pickups because
"enemy"and"pickup"aren't paired.
5. Collider files: Content/Colliders/*.collider
One file per kind of collider. Many objects can load the same file, and each one gets its own collider.
return
{
shape = "sphere", -- "sphere" or "box" (required)
radius = 0.5, -- spheres only (required for a sphere)
-- halfSize = { x = 0.5, y = 0.5, z = 0.5 }, -- boxes only: half of the box's size along each axis (required for a box)
-- center = { x = 0.0, y = 0.0, z = 0.0 }, -- optional offset from the object's position (missing components are 0)
layer = "player", -- one of the names in game.layers (required)
-- isTrigger = false, -- optional: true reports overlaps but never pushes and is never pushed
-- isStatic = false, -- optional: true for things that never move (floors, walls); they are never pushed
}
| Key | Type | Notes |
|---|---|---|
shape | "sphere" or "box" | Boxes are axis-aligned: they don't rotate with their object. |
radius | number > 0 | Spheres only. Use your sphere mesh's radius. |
halfSize | { x, y, z }, all > 0 | Boxes only. A 1 x 1 x 1 cube has halfSize = { x = 0.5, y = 0.5, z = 0.5 }. |
center | { x, y, z } | Use it when the mesh's origin isn't the middle of the shape (e.g. a floor plane whose box hangs below it). |
layer | string | Must be a layer in game.layers. |
isTrigger | boolean | Default false. |
isStatic | boolean | Default false. Two static colliders are never tested against each other. |
ColliderBuilder checks everything and reports problems in Visual Studio's Error List with the file and line. Double-clicking an error opens the file at that line. It catches misspelled keys (isTriger), a layer that isn't in the layers file, a negative radius, a sphere with a halfSize, Lua syntax errors, and similar mistakes. For example:
Colliders/pickup.collider(13): error : The collider file has an unknown key "isTriger" (the valid keys are: "shape", "radius", "halfSize", "center", "layer", "isTrigger", "isStatic")
Colliders/player.collider(15): error : The layer "plaeyr" isn't in the game's layers file (Collision/game.layers); the layers are: "world", "player", "enemy", "pickup"
6. AssetsToBuild.lua
Add these two tables next to shaders and meshes, and list the files that are really in your content folder:
collisionlayers =
{
"Collision/game.layers",
},
colliders =
{
"Colliders/player.collider",
"Colliders/crate.collider",
-- ...
},
The built files end up at data/Collision/game.binlayers and data/Colliders/<name>.bincollider.
7. Using it in your game
#include <Engine/Collision/Collision.h>
The easiest place to keep a collider is next to the rigid body that it follows, for example a Collision::cCollider* collider = nullptr; member in your game object struct, or a member of your game class.
Initialize(): initialize the system first, then load colliders and attach them to rigid bodies:
if ( !( result = Collision::Initialize( "data/Collision/game.binlayers" ) ) )
return result;
Collision::cCollider* playerCollider = nullptr;
if ( !( result = Collision::cCollider::Load( "data/Colliders/player.bincollider", m_player.rigidBodyState, playerCollider ) ) )
return result;
playerCollider->userData = &m_player; // so that an event or a raycast can find your object
The collider follows the rigid body: its center is always rigidBodyState.position + center. The rigid body must stay where it is in memory while the collider exists. A member of your game class, an element of a fixed-size array, or an object that you allocated with new (or a std::unique_ptr) is fine. An element of a std::vector of objects that can grow is not, because the vector moves its elements when it grows.
If the game is run before its assets have been built, Initialize() and Load() write what is missing to the log and return a failure. Return it from your Initialize() like the code above does, and the application shows its "initialization failed" message instead of crashing.
UpdateSimulationBasedOnTime(): move everything, then call Collision::Update() once:
m_player.rigidBodyState.Update( i_elapsedSecondCount_sinceLastUpdate );
m_enemy.rigidBodyState.Update( i_elapsedSecondCount_sinceLastUpdate );
Collision::Update(); // pushes solid colliders apart, then sends the events
CleanUp(): release your references, then clean up the system:
playerCollider->DecrementReferenceCount();
playerCollider = nullptr;
// ... every other collider ...
Collision::CleanUp();
Colliders are reference counted like meshes and effects. Load() gives you one reference. To remove a collider from the world at any time (a collected pickup, a destroyed enemy), call DecrementReferenceCount(). The system removes it safely at its next update and sends OnExit to everything it was touching, and it never reads that rigid body again, so you can delete the object right away. To switch a collider off for a while, use SetEnabled( false ) instead. If you forget to release a collider before Collision::CleanUp(), the log says how many were still held.
8. Events
playerCollider->OnEnter = [this]( const Collision::sContact& i_contact )
{
// i_contact.other: the other collider (use other->userData to find its object)
// i_contact.normal: unit vector from the other collider toward this one
// i_contact.penetrationDepth: how far they overlapped before they were pushed apart
if ( i_contact.other == m_enemy.collider )
{
if ( i_contact.normal.y > 0.7f )
BounceOffEnemysHead(); // landed on top
else
GetHurt();
}
};
playerCollider->OnStay = [this]( const Collision::sContact& i_contact ) { /* every update while touching */ };
playerCollider->OnExit = [this]( const Collision::sContact& i_contact ) { /* normal and depth are 0 here */ };
- Both colliders of a pair get the event, each from its own point of view (opposite normals).
- In one update all exits are sent first, then all enters, then all stays.
- Resting on something counts as touching (shapes within 0.001 units of each other touch). A ball sitting on the floor gets one
OnEnterand thenOnStayevery update, without flickering. - Inside an event you may move objects, change velocities, enable or disable colliders, release colliders (even the other one), load new ones and raycast. Changes take effect in the next update. You may not call
Collision::Update()orCollision::CleanUp()from inside an event (it asserts). - The events are
std::functions, so a lambda that capturesthisis the easiest. Any of them can be left empty.
9. Raycasts
Collision::sRaycastHit hit;
if ( Collision::Raycast( origin, direction, maxDistance, hit, Collision::GetLayerMask( "world" ) ) )
{
// hit.collider, hit.point, hit.normal (pointing back toward the ray), hit.distance
}
directioncan be any length except 0. It is normalized for you.- The layer mask says which layers can be hit. The default is every layer. Masks combine with
|:GetLayerMask( "world" ) | GetLayerMask( "enemy" ). GetLayerMask()looks the name up every time it is called (and asserts if there is no such layer). If you raycast every update, look the masks up once afterInitialize()and keep them in members.- Disabled colliders are never hit. Triggers are skipped unless you pass
trueas the last argument. - A ray that starts inside a collider doesn't hit that collider, so a ray cast from your object's center never hits its own collider.
- It changes nothing, so you can call it any time after
Initialize(), including from inside an event. hit.collideris valid until the nextCollision::Update().
Ground check (jump only when standing on something):
Collision::sRaycastHit hit;
const bool isOnGround = Collision::Raycast( m_player.rigidBodyState.position, Math::sVector( 0.0f, -1.0f, 0.0f ),
playerRadius + 0.05f, hit, Collision::GetLayerMask( "world" ) );
Line of sight (can the enemy see the player, or is a wall in the way?):
const auto toPlayer = m_player.rigidBodyState.position - m_enemy.rigidBodyState.position;
Collision::sRaycastHit hit;
const bool canSeePlayer = Collision::Raycast( m_enemy.rigidBodyState.position, toPlayer, toPlayer.GetLength(), hit,
Collision::GetLayerMask( "world" ) | Collision::GetLayerMask( "player" ) )
&& ( hit.collider == m_player.collider );
10. Common tasks
Short recipes. The names (m_coin, m_layerMask_world, ...) are made up; the patterns are the ones my demo uses.
A pickup (a coin, a key, a checkpoint). Give it a static trigger in a "pickup" layer that only "player" interacts with, so nothing else can ever enter it:
m_coin.collider->OnEnter = [this]( const Collision::sContact& )
{
++m_score;
m_coin.isVisible = false; // (your own flag: stop submitting its mesh)
m_coin.collider->SetEnabled( false ); // it can't be collected again until you enable it
};
Which object did I touch? Set userData when you load a collider, and cast it back in the event:
auto* const otherObject = static_cast<sGameObject*>( i_contact.other->userData );
const bool isEnemy = ( i_contact.other->GetLayerMask() & m_layerMask_enemy ) != 0;
Gravity and jumping. Gravity is just an acceleration. The ground check above decides whether a jump is allowed, and clamping the falling speed keeps fast falls from tunneling through floors (section 12):
// Initialize()
m_player.rigidBodyState.acceleration = Math::sVector( 0.0f, -12.0f, 0.0f );
// UpdateSimulationBasedOnInput()
if ( m_isPlayerOnGround && UserInput::IsKeyPressed( UserInput::KeyCodes::Space ) )
m_player.rigidBodyState.velocity.y = 6.5f;
// UpdateSimulationBasedOnTime(), before moving the player
auto& velocity = m_player.rigidBodyState.velocity;
velocity.y = std::max( velocity.y, -12.0f );
A floor or a crate that the player lands on removes the falling velocity, so the player comes to rest on top of it without bouncing or sinking.
An enemy that turns around at walls (and at ledges). Look a little ahead with a ray that only sees the world:
Collision::sRaycastHit hit;
const Math::sVector ahead( m_enemyDirection, 0.0f, 0.0f );
const bool isWallAhead = Collision::Raycast( enemyPosition, ahead, enemyRadius + 0.1f, hit, m_layerMask_world );
// (a ray cast straight down from a point just in front of the enemy finds a ledge: nothing below means no floor)
const bool isFloorAhead = Collision::Raycast( enemyPosition + ahead * ( enemyRadius + 0.1f ), Math::sVector( 0.0f, -1.0f, 0.0f ),
enemyRadius + 0.2f, hit, m_layerMask_world );
if ( isWallAhead || !isFloorAhead )
m_enemyDirection = -m_enemyDirection;
Landing on an enemy vs. being hit by it. The contact normal points from the other collider toward the one being told, so in the player's OnEnter a normal that points mostly up means that the player came from above (see the example in section 8; my demo uses normal.y >= 0.7).
Moving platforms and doors. Use a static collider and move its rigid body yourself (set its velocity, or its position). Static colliders are never pushed, and dynamic colliders are pushed out of their way. A platform doesn't carry what stands on it sideways: if you need that, add the platform's velocity to the rider's.
Removing an object for good. collider->DecrementReferenceCount() and forget the pointer. Everything it was touching gets OnExit at the next update.
Many objects with the same collider. Load the same file once per object. Keep the objects somewhere that doesn't move in memory (section 7):
sGameObject m_crates[s_crateCount]; // a fixed array never moves its elements
for ( auto& crate : m_crates )
{
if ( !( result = Collision::cCollider::Load( "data/Colliders/crate.bincollider", crate.rigidBodyState, crate.collider ) ) )
return result;
crate.collider->userData = &crate;
}
11. How the solid response works
Collision::Update() first finds every pair that touches. Then, for every pair where neither collider is a trigger:
| Pair | What happens |
|---|---|
| dynamic and static | The dynamic collider is moved all of the way out along the contact normal, and the part of its velocity that points into the static one is removed. It slides along walls and comes to rest on floors without bouncing or sinking. |
| dynamic and dynamic | Each is moved half of the way, and the speed at which they were approaching each other is taken from both equally, as if they had the same mass. |
| anything and a trigger | Nothing is pushed. Only the events are sent. |
| static and static | Never tested. |
A collider in a corner touches two things at once. The overlaps are resolved again (up to 4 passes), each time from where the colliders are after the last pass. Only position and velocity are changed, never acceleration or orientation.
Why the velocity changes too: our rendering extrapolates every object by its velocity (PredictFutureTransform()), so an object that kept its velocity into a floor would be drawn sinking into the floor between simulation updates.
Design tips:
- Make everything that never moves
isStatic = true. It is cheaper, and it means "never pushed". - Let input set velocities every update, as usual. If the player holds "right" against a wall, it is pushed back out every update and stays touching the wall.
12. Limits, and how to stay inside them
- Tunneling: collisions are checked once per simulation update. If something moves farther than about half the thickness of what it should hit in one update, it can end up past the middle and be pushed out of the wrong side. Make floors and walls thick (my floor is a whole unit thick), clamp falling speed, and consider a faster simulation rate. My demo overrides
GetSimulationUpdatePeriod_inSeconds()to return 1/60 (the default is 1/15). - Boxes don't rotate. For an object that spins around its vertical axis, use a box that encloses it in every direction, or a sphere.
- Two dynamic colliders are treated as if they had the same mass. There are no masses, so a heavy object and a light one push each other equally.
- A single ground-check ray can miss a ledge that only the edge of a sphere rests on. Cast a second ray a little to each side if that matters in your game.
- Every pair of colliders is tested every update (a cheap bounding-box test rejects most pairs). That is fine for dozens or a few hundred colliders. There is no broad phase.
- At most 32 layers.
- Call everything from the simulation thread (the thread that runs
UpdateSimulationBasedOnTime()).
13. Troubleshooting
When something builds wrong:
| Problem | Things to check |
|---|---|
attempt to call a nil value (global 'NewAssetTypeInfo') when the assets build | The block from section 3 is above the place where NewAssetTypeInfo() is defined. Move it to just after your mesh asset type. |
No asset type info has been defined for "colliders" (or "collisionlayers") | The block from section 3 isn't in AssetBuildFunctions.lua. |
The builder "...ColliderBuilder.exe" doesn't exist | BuildMyGameAssets doesn't depend on ColliderBuilder (setup step 4), so the assets were built before the builder. |
Cannot open include file: 'Engine/Collision/Collision.h' | The library isn't at Engine\Collision in your solution's folder. |
unresolved external symbol with eae6320::Collision:: in it | Your game project doesn't reference Collision (setup step 3). |
The game's layers file couldn't be found | The layers file must be Collision/game.layers in your game's content folder. |
| A collider error in the Error List | Double-click it. The message names the key or layer that is wrong. |
When something runs wrong:
| Problem | Things to check |
|---|---|
| The game says initialization failed | Build BuildMyGameAssets. Check the paths you pass to Initialize() and Load(). The log (eae6320.log) says which file failed and why. |
| Two objects pass through each other | Are their layers paired in interactions? Is one of them a trigger? Are both static? Is one disabled? Are you calling Collision::Update() after moving them? Is something moving too fast (section 12)? |
| A raycast misses | Does the layer mask include the layer? Is the target a trigger (pass true)? Does the ray start inside the target? Is maxDistance long enough? |
| An object is drawn sinking into a wall | Is the wall's collider as big as its mesh? Is the object's collider dynamic (isStatic not set)? |
| Events arrive one update late | Changes made inside an event (moving, disabling, releasing) take effect in the next Update(), by design. |
| A collider is in the wrong place | Its center is the rigid body's position plus center. Is the rigid body that you passed to Load() the one that you move? |
The log lists your layers and what each one touches when the system is initialized, which is the first thing to look at when something doesn't collide.
14. The interface at a glance
| Call | What it does |
|---|---|
Collision::Initialize( path ) | Loads the built layers file. Call it before loading any collider. |
Collision::Update() | Once per simulation update, after moving your objects: pushes solid colliders apart, then sends the events. |
Collision::CleanUp() | Removes every collider (without events). Release your references first. |
Collision::Raycast( origin, direction, maxDistance, o_hit, layerMask, shouldTriggersBeHit ) | The closest hit, if any. |
Collision::GetLayerMask( name ), GetLayerIndex( name, o_index ), GetLayerName( index ), DoLayersInteract( a, b ) | Layer lookups. |
cCollider::Load( path, rigidBody, o_collider ) | Loads a built collider, attaches it to the rigid body and adds it to the world. |
collider->OnEnter, OnStay, OnExit | The event functions (std::function<void( const sContact& )>). |
collider->userData | Your own pointer. The system never looks at it. |
collider->SetEnabled( bool ), IsEnabled() | Switch a collider off and on. |
GetShape(), GetRadius(), GetHalfSize(), GetCenterOffset(), GetCenter(), GetLayer(), GetLayerMask(), IsTrigger(), IsStatic(), GetRigidBody(), GetId() | What the collider is and where it is now. |
IncrementReferenceCount(), DecrementReferenceCount() | Reference counting, like meshes and effects. |
Every header has comments written for someone using the system: Collision.h (the system and raycasts) and cCollider.h (colliders, lifetime, events and the response) are the two to read.