Benjamin Yang · EAE 6320

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:

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

FolderWhat 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)

  1. Copy Engine/Collision and Tools/ColliderBuilder to the same places in your own solution.
  2. In Visual Studio: Add > Existing Project... for Engine/Collision/Collision.vcxproj (put it in the Engine folder) and Tools/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.
  3. Your game project: Add > Reference... > Collision.
  4. BuildMyGameAssets: Build Dependencies > Project Dependencies... and tick ColliderBuilder, the same way it depends on MeshBuilder.
  5. Paste the block in section 3 at the end of Tools/AssetBuildLibrary/AssetBuildFunctions.lua.
  6. Write Content/Collision/game.layers (section 4) and a collider file for every kind of collider (section 5), and list them in AssetsToBuild.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
    },
}

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

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 */ };

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

Design tips:

11. Limits, and how to stay inside them

12. Troubleshooting

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 11)?
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?
A collider error in the Error ListDouble-click it. The message names the key or layer that is wrong.
Events arrive one update lateChanges 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.