Benjamin Yang · EAE 6320

Collision System: User Guide

⬇ Download the code the Collision library, ColliderBuilder, the block for AssetBuildFunctions.lua, example data and the 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:

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 fileWhat 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.luaThe 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.

  1. Copy Engine\Collision into your solution's Engine folder and Tools\ColliderBuilder into its Tools folder (next to MeshBuilder).
  2. 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 choose Tools\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.props like every other project, so they build for x64 (Direct3D) and x86 (OpenGL) in Debug and Release, and ColliderBuilder.exe ends up next to MeshBuilder.exe.
  3. Right-click your game project (MyGame) > Add > Reference... and tick Collision.
  4. 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.
  5. Paste the asset types into Tools\AssetBuildLibrary\AssetBuildFunctions.lua (section 3 says where).
  6. Copy ExampleContent\Collision and ExampleContent\Colliders into MyGame_\Content (or write your own files, sections 4 and 5), and add the two tables from ExampleContent\AssetsToBuild_Collision.lua to MyGame_\Content\AssetsToBuild.lua (section 6).
  7. Build the solution. Your game's data folder now has Collision\game.binlayers and a .bincollider for every collider file.
  8. Add the code to your game (section 7). When you run it, the first lines that the collision system writes to eae6320.log list 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
    },
}

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
}
KeyTypeNotes
shape"sphere" or "box"Boxes are axis-aligned: they don't rotate with their object.
radiusnumber > 0Spheres only. Use your sphere mesh's radius.
halfSize{ x, y, z }, all > 0Boxes 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).
layerstringMust be a layer in game.layers.
isTriggerbooleanDefault false.
isStaticbooleanDefault 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 */ };

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
}

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:

PairWhat happens
dynamic and staticThe 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 dynamicEach 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 triggerNothing is pushed. Only the events are sent.
static and staticNever 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:

12. Limits, and how to stay inside them

13. Troubleshooting

When something builds wrong:

ProblemThings to check
attempt to call a nil value (global 'NewAssetTypeInfo') when the assets buildThe 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 existBuildMyGameAssets 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 itYour game project doesn't reference Collision (setup step 3).
The game's layers file couldn't be foundThe layers file must be Collision/game.layers in your game's content folder.
A collider error in the Error ListDouble-click it. The message names the key or layer that is wrong.

When something runs wrong:

ProblemThings to check
The game says initialization failedBuild 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 otherAre 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 missesDoes 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 wallIs the wall's collider as big as its mesh? Is the object's collider dynamic (isStatic not set)?
Events arrive one update lateChanges made inside an event (moving, disabling, releasing) take effect in the next Update(), by design.
A collider is in the wrong placeIts 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

CallWhat 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, OnExitThe event functions (std::function<void( const sContact& )>).
collider->userDataYour 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.