Collision System: User Guide
First version (Engine System Update #2, November 2026). Benjamin Yang. Questions are welcome on Slack or by email.
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.
1. The two projects
| Folder | What it is |
|---|---|
Engine/Collision/ | The run-time static library. Collision.h is the only header your game includes. |
Tools/ColliderBuilder/ | The builder that turns the human-readable .layers and .collider files into small binary files at build time. |
Neither project has any platform-specific code in its interface. Both are built for every platform and configuration like the rest of the solution. My demo's data files (MyGame_/Content/Collision/game.layers and MyGame_/Content/Colliders/*.collider) are good examples to copy and change. The ZIP with both projects will come with the final write-up.
2. Setting up your solution (once)
- Copy
Engine/CollisionandTools/ColliderBuilderto the same places in your own solution. - In Visual Studio: Add > Existing Project... for
Engine/Collision/Collision.vcxproj(put it in the Engine folder) andTools/ColliderBuilder/ColliderBuilder.vcxproj(put it in the Tools folder).- Collision references Asserts, Logging, Math, Physics, Platform, Results and Windows, which you already have from Assignment 01.
- ColliderBuilder references Asserts, Platform, Windows, LuaLib and AssetBuildLibrary, the same as MeshBuilder.
- Your game project: Add > Reference... > Collision.
- BuildMyGameAssets: Build Dependencies > Project Dependencies... and tick ColliderBuilder, the same way it depends on MeshBuilder.
- Paste the block in section 3 at the end of
Tools/AssetBuildLibrary/AssetBuildFunctions.lua. - Write
Content/Collision/game.layers(section 4) and a collider file for every kind of collider (section 5), and list them inAssetsToBuild.lua(section 6).
3. What to add to AssetBuildFunctions.lua
-- 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, 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
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. Because of RegisterReferencedAssets(), the layers file is built 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 doesn't matter.
- Raycasts don't use the interactions. They filter by layer mask instead (section 9).
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. |
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.
6. AssetsToBuild.lua
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>
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, or an element of a fixed array, is fine. An element of a std::vector that can grow is not, because the vector moves its elements when it grows.
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. To switch a collider off temporarily, use SetEnabled( false ) instead.
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. A ball sitting on the floor gets one
OnEnterand thenOnStayevery update. - Inside an event you may move objects, enable or disable colliders, release colliders (even the other one) and raycast. Changes take effect in the next update. You may not call
Collision::Update()orCollision::CleanUp()from inside an event.
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" ). - 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.
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. 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.
Design tips:
- Make everything that never moves
isStatic = true. It is cheaper, and it means "never pushed". - Moving platforms, doors, elevators: use a static collider and move its rigid body yourself. It is never pushed, and dynamic colliders are pushed out of it.
- 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.
11. 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. - 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.
- Every pair of colliders is tested every update. That is fine for dozens or a few hundred colliders. A broad phase is on my list of stretch goals.
- At most 32 layers.
- Call everything from the simulation thread (the thread that runs
UpdateSimulationBasedOnTime()).
12. Troubleshooting
| 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 11)? |
| 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? |
| A collider error in the Error List | Double-click it. The message names the key or layer that is wrong. |
| Events arrive one update late | Changes made inside an event (moving, disabling, releasing) take effect in the next Update(), by design. |
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.