Tutorials

Using ColMesh for character collisions

BBMOD 3.24.0 Intermediate Collisions

Created: 16.5.2026


BBMOD does not ship with a built-in character collision system, but it integrates cleanly with ColMesh v2, a GML library for mesh-based 3D collisions in GameMaker. BBMOD provides dedicated helper functions to feed your loaded models and terrain geometry directly into a ColMesh container, so you do not have to handle vertex extraction yourself.

In this tutorial you will build a complete character collision setup: create a ColMesh container from a set of BBMOD models and a terrain, define a capsule collider for your player, move the player with gravity, and resolve collisions against the geometry each frame.

NOTE: ColMesh v2 is included in BBMOD since version 3.24.0. No separate download or import is required.

Contents

Building the collision mesh

A ColMesh container organises the collision primitives that make up your level geometry. ColMesh offers several container types that differ in how they partition space for fast queries:

Container Best use
cm_octree(regionSize) Large 3D levels with geometry spread across all three axes
cm_spatialhash(regionSize) Levels with a known density; very fast inserts and removals
cm_quadtree(regionSize) Mostly flat/horizontal levels
cm_list() Small levels or pre-filtered subsets

For most 3D games an octree is the right default. The regionSize argument controls the spatial subdivision cell size; a value around 100 to 500 game units typically works well and should roughly match the scale of individual geometry clusters in your level.

/// @desc Create event
global.colmesh = cm_octree(200);

Using global.colmesh lets multiple objects (player, NPCs, projectiles) all query the same level geometry without passing the container around.

Adding model geometry

Real levels are typically composed of multiple models: a ground mesh, buildings, cliffs, props, and so on. Each model can be fed into the same ColMesh container with bbmod_model_to_colmesh2.

WARNING: You must call bbmod_model_to_colmesh2 before calling freeze() on the model. Freezing a model uploads its vertex buffers to GPU-only memory, after which the CPU-side triangle data required for collision extraction is no longer readable.

The typical per-model workflow is therefore: load, extract collision geometry, then freeze.

/// @desc Create event (level controller object)

// Ground mesh
var _matGround = matrix_build(0, 0, 0, 0, 0, 0, 1, 1, 1);
modGround = new BBMOD_Model("Data/Ground.bbmod");
bbmod_model_to_colmesh2(modGround, global.colmesh, _matGround);
modGround.freeze();

// A building placed at a specific world position
var _matBuilding = matrix_build(500, 200, 0, 0, 0, 45, 1, 1, 1);
modBuilding = new BBMOD_Model("Data/Building.bbmod");
bbmod_model_to_colmesh2(modBuilding, global.colmesh, _matBuilding);
modBuilding.freeze();

// Cliff geometry repeated at several positions
modCliff = new BBMOD_Model("Data/Cliff.bbmod");
var _cliffPositions = [
    [100, 300, 0],
    [150, 320, 0],
    [200, 310, 0],
];
var i = 0;
repeat(array_length(_cliffPositions))
{
    var _pos = _cliffPositions[i++];
    var _mat = matrix_build(_pos[0], _pos[1], _pos[2], 0, 0, 0, 1, 1, 1);
    bbmod_model_to_colmesh2(modCliff, global.colmesh, _mat);
}
modCliff.freeze();

The third argument to bbmod_model_to_colmesh2 is the world transform matrix. Pass the same matrix that you will use when drawing the model so the collision triangles are placed at the correct world position. When you draw without a transform, pass undefined or omit the argument.

If you only want a specific mesh from a model to participate in collisions, for example a low-poly collision proxy, use bbmod_mesh_to_colmesh2 and pass the individual BBMOD_Mesh directly. The same freeze-after rule applies.

// Add only the first mesh as collision, then freeze
bbmod_mesh_to_colmesh2(modGround.Meshes[0], global.colmesh, _matGround);
modGround.freeze();

Adding terrain geometry

Pass the heightmap sprite directly to the BBMOD_Terrain constructor to build a fully initialised terrain in one call. The constructor runs smoothing, normal generation, and mesh building automatically.

/// @desc Create event (level controller object)

terrain = new BBMOD_Terrain(SprHeightmap, 0, 16);
terrain.Scale.Set(16);
terrain.Position.Set(
    -terrain.Size.X * terrain.Scale.X * 0.5,
    -terrain.Size.Y * terrain.Scale.Y * 0.5,
    0);

// Feed the terrain into the colmesh
bbmod_terrain_to_colmesh2(terrain, global.colmesh);

bbmod_terrain_to_colmesh2 reads Position and Scale from the terrain struct directly, so no separate transform matrix is needed. Call it after setting Position and Scale. There is no freeze restriction for terrain.

TIP: If your level uses both BBMOD models and a terrain, add all of them to the same container. ColMesh handles mixed geometry transparently.

Creating the player collider

The player is represented as a capsule collider created with cm_collider. The capsule is defined by a centre position, an up-vector, a radius and a height. Two additional parameters, slopeAngle and precision, control how steep a surface the player can walk up and how many substeps are used during collision resolution.

/// @desc Create event (player object)
z = 500;
zspd = 0;

var _radius = 12;
var _height = 30;
var _slopeAngle = 46;
var _precision = 4;

collider = cm_collider(
    x, y, z,
    0, 0, 1,
    _radius, _height, _slopeAngle, _precision,
    CM_GROUP_SOLID);

CM_GROUP_SOLID is a bitmask constant defined by ColMesh. All geometry added through bbmod_model_to_colmesh2 and bbmod_terrain_to_colmesh2 is placed in this group by default, so the collider will test against it automatically.

The collider is a plain GML array. You can read its fields by indexing it with the CM enum:

Field Description
collider[CM.X], CM.Y, CM.Z World position after collision resolution
collider[CM.GROUND] true when the collider is resting on a surface
collider[CM.NX], CM.NY, CM.NZ Surface normal of the last collision

Moving with collision resolution

Each frame you accumulate velocity, apply it to the position variables, and then call cm_collider_step_towards to move the collider toward the new position while resolving any geometry it would pass through. The function returns true if a collision occurred and writes the safe resolved position back into the collider array.

/// @desc Step event (player object)

// Verlet-style velocity: multiply by friction each step
var _friction = 0.7;
xspd *= _friction;
yspd *= _friction;

// Gravity
zspd -= 0.5;

// Read movement input
var _h = keyboard_check(ord("D")) - keyboard_check(ord("A"));
var _v = keyboard_check(ord("W")) - keyboard_check(ord("S"));

// Normalise diagonal input
if (_h != 0 && _v != 0)
{
    var _s = 1 / sqrt(2);
    _h *= _s;
    _v *= _s;
}

var _accel = 2;
xspd += _accel * _h;
yspd -= _accel * _v;

// Apply velocity
x += xspd;
y += yspd;
z += zspd;

// Resolve collisions
if (cm_collider_step_towards(collider, global.colmesh, x, y, z))
{
    x = collider[CM.X];
    y = collider[CM.Y];
    z = collider[CM.Z];

    if (collider[CM.GROUND] && zspd < 0)
    {
        zspd = 0;
    }
}

TIP: Always read x, y, z back from collider[CM.X], collider[CM.Y], collider[CM.Z] after cm_collider_step_towards. The function resolves the position inside the collider array; the instance variables are not updated automatically.

Jumping and ground detection

collider[CM.GROUND] is set to true by ColMesh whenever the capsule's bottom is resting on a walkable surface. Use this flag to gate jump input, so the player can only jump while standing on the ground.

/// @desc Step event (player object) - add inside the step loop above

var _jump = keyboard_check_pressed(vk_space);
if (_jump && collider[CM.GROUND])
{
    zspd = 12;
}

NOTE: The CM.GROUND flag is recomputed inside cm_collider_step_towards on every call. Do not cache it across frames; always read it fresh after the call.

Raycasting against the scene

ColMesh supports raycasts with cm_cast_ray. Create a ray with cm_ray(x1, y1, z1, x2, y2, z2), cast it against the container, and then read the result with cm_ray_get_hit, cm_ray_get_x, cm_ray_get_y and cm_ray_get_z.

A common use case is a camera obstacle check - cast a ray from the player to the desired camera position and clamp the camera distance if anything is in the way:

/// @desc Step event (camera logic)

var _camTargetX = x + camOffsetX;
var _camTargetY = y + camOffsetY;
var _camTargetZ = z + camOffsetZ;

var _ray = cm_ray(x, y, z + 25, _camTargetX, _camTargetY, _camTargetZ);
_ray = cm_cast_ray(global.colmesh, _ray);

if (cm_ray_get_hit(_ray))
{
    camX = cm_ray_get_x(_ray);
    camY = cm_ray_get_y(_ray);
    camZ = cm_ray_get_z(_ray);
}
else
{
    camX = _camTargetX;
    camY = _camTargetY;
    camZ = _camTargetZ;
}

Another common use case is a ground probe for placing objects on terrain:

var _ray = cm_ray(_xpos, _ypos, 5000, _xpos, _ypos, -5000);
_ray = cm_cast_ray(global.colmesh, _ray);
if (cm_ray_get_hit(_ray))
{
    var _groundZ = cm_ray_get_z(_ray);
}

TIP: cm_cast_ray always returns the ray array so you can chain the call, but it modifies the array in place. Creating a new ray each frame with cm_ray(...) is inexpensive.

Triggers

ColMesh supports trigger volumes through its group and callback system. Any primitive added to the container with CM_GROUP_TRIGGER becomes a trigger. Attach a callback function to it with cm_trigger_set, then call cm_collider_activate_triggers each frame to fire any callbacks the collider is overlapping.

/// @desc Create event (level controller object)

var _trigger = cm_sphere(triggerX, triggerY, triggerZ, 40);
cm_trigger_set(_trigger, function()
{
    show_debug_message("Player entered trigger!");
});
cm_add(global.colmesh, _trigger);
/// @desc Step event (player object) - call after cm_collider_step_towards

cm_collider_activate_triggers(collider, global.colmesh, CM_GROUP_TRIGGER);

NOTE: CM_GROUP_SOLID and CM_GROUP_TRIGGER are separate bitmask flags. Pass the appropriate mask to each call so that movement resolution only tests solid geometry and trigger activation only tests trigger volumes.

Debugging collision geometry

ColMesh can draw all collision primitives in a container as coloured wireframe geometry. This is useful during development to verify that your collision mesh matches the visible level geometry.

The debug view has two layers:

  • Full geometry - the entire colmesh baked once to a vertex buffer and drawn with a solid tint. Shows the complete collision shape of your level at a glance.
  • Active region - the triangle candidates that the spatial partition would test against the tracked collider's current AABB, highlighted in per-triangle colours. This rebuilds automatically whenever the player moves into a new spatial cell, so it always reflects what ColMesh is actually testing.
/// @desc Create event

colmeshDebugBuffer = -1;
showColmeshDebug = false;

currentRegion = cm_list();
bakedRegion = -1;
/// @desc Step event - toggle on F4

if (keyboard_check_pressed(vk_f4))
{
    showColmeshDebug = !showColmeshDebug;
}

Draw both layers after renderer.render() has returned. Which surface to target depends on the renderer type:

  • BBMOD_DeferredRenderer - draw to renderer.__surFinal, the internal surface holding the fully composited frame.
  • BBMOD_DefaultRenderer - draw to application_surface.

Also explicitly enable depth write and depth test. After renderer.render() the GPU state may have depth writes disabled (common in transparent and post-process passes), so re-enabling them here makes the overlay occlude correctly against opaque scene geometry.

/// @desc Draw event (place this after renderer.render() returns)

if (showColmeshDebug)
{
    // BBMOD_DeferredRenderer: use renderer.__surFinal
    // BBMOD_DefaultRenderer:  use application_surface
    surface_set_target(renderer.__surFinal);
    gpu_push_state();
    gpu_set_zwriteenable(true);
    gpu_set_ztestenable(true);
    camera.apply();

    // Layer 1: full geometry baked once, drawn with a tint
    if (colmeshDebugBuffer < 0)
    {
        colmeshDebugBuffer = vertex_create_buffer();
        cm_vbuff_begin(colmeshDebugBuffer);
        cm_vbuff_bake(global.colmesh, colmeshDebugBuffer, matrix_build_identity(), CM_GROUP_SOLID, 1, 1, c_lime);
        cm_vbuff_end(colmeshDebugBuffer);
    }
    shader_set(sh_cm_debug);
    shader_set_uniform_f(shader_get_uniform(sh_cm_debug, "u_radius"), 0);
    shader_set_uniform_f(shader_get_uniform(sh_cm_debug, "u_color"),
        color_get_red(c_lime) / 255,
        color_get_green(c_lime) / 255,
        color_get_blue(c_lime) / 255,
        0.5);
    cm_vbuff_submit(colmeshDebugBuffer);
    shader_reset();

    // Layer 2: active region - triangle candidates for the tracked collider
    // Replace `collider` with the collider you want to track (e.g. the player's)
    var _region = cm_get_region(global.colmesh, cm_collider_get_aabb(collider));
    var _num = _region[CM_LIST.SIZE];
    array_resize(_region, _num);
    if (_num > CM_LIST.NUM && (!array_equals(_region, currentRegion) || bakedRegion < 0))
    {
        array_resize(currentRegion, array_length(_region));
        array_copy(currentRegion, 0, _region, 0, array_length(_region));
        if (bakedRegion >= 0)
        {
            vertex_delete_buffer(bakedRegion);
        }
        bakedRegion = vertex_create_buffer();
        cm_vbuff_begin(bakedRegion);
        cm_vbuff_bake(currentRegion, bakedRegion);
        cm_vbuff_end(bakedRegion);
    }
    if (_num > CM_LIST.NUM)
    {
        cm_vbuff_submit(bakedRegion);
    }

    gpu_pop_state();
    surface_reset_target();
}

The full-geometry layer uses CM_GROUP_SOLID as the mask to exclude trigger volumes. It is drawn with sh_cm_debug and a uniform colour tint. The active region layer omits the shader and mask so each triangle is drawn using the per-triangle HSV colour baked into its vertex data, making the active candidates visually distinct from the rest of the level.

NOTE: renderer.__surFinal is an internal BBMOD field. It is suitable for debug tooling but should not be relied upon in shipping code.

Performance tips

  • Build the colmesh once, at load time. Adding geometry is an expensive operation; do it in the Create event of a persistent controller object and never repeat it during gameplay.
  • Match regionSize to your level scale. A value that is too small creates an overly deep tree with many nodes; too large and spatial subdivision offers no benefit. Aim for each region to contain roughly 10 to 50 triangles once the level is populated.
  • Use a separate container for dynamic geometry. Static level geometry lives in the main octree. Moving platforms or destructible objects should be wrapped in a cm_dynamic container that is added to the main colmesh. Update only those containers each frame rather than rebuilding the whole tree.
  • Add collision geometry before freezing. Call bbmod_model_to_colmesh2 or bbmod_mesh_to_colmesh2 before calling freeze() on the model. Once frozen the vertex data is GPU-only and cannot be read back for collision extraction.
  • For very large terrains, add only the relevant terrain chunks. If your terrain is divided into BBMOD_Terrain chunks, you can call bbmod_terrain_to_colmesh2 per chunk and add all chunks to the same octree. The spatial partitioning then handles efficient region queries at query time.