Repository navigation
CollisionHelper
CollisionHelper provides a complete suite of collision detection and resolution functions for 2D games. It handles everything from basic overlap checks to advanced swept collisions that prevent tunneling.
Collision is one of the most common and error-prone parts of game development. CollisionHelper centralizes all collision logic in one place, making it easy to:
- Detect when shapes overlap
- Resolve overlaps by pushing objects apart
- Prevent tunneling with swept collisions
- Raycast for line-of-sight and aiming
- Slide along walls with move-and-slide
- All methods use
Rect2andVect2- no separateCirclestruct is needed.
Unlike monolithic CollisionWorld or PhysicsManager classes, CollisionHelper is intentionally designed as a stateless, static utility class.
Most engines force you into a rigid spatial tree, quadtree, or a massive entity list just to check if two objects overlap. This means your game allocates massive amounts of memory upfront just for "potential" collisions, and spends CPU cycles updating a hierarchy even when nothing is touching.
By keeping CollisionHelper as a pure-math static class, we avoid all that overhead. When you call a function like RectRect, you are doing a handful of stack-allocated comparisons that return an instant answer. You don't need to initialize a manager, you don't need to worry about memory allocation, and you get O(1) performance regardless of how many entities are in your scene.
This keeps the system incredibly fast, lightweight, and flexible. It doesn't force a specific data structure onto your game; it just provides a toolbox of pure math functions that you can call whenever you need them.
We follow the KISS (Keep It Simple, Stupid) principle here. Because the system is loose, the game developer is in complete control:
- Want to do a quick line-of-sight check for an NPC? Call
LineRect. - Want to test if a bullet hits a circle? Call
CircleCircle. - Don't need physics this frame? Don't call anything. There is zero engine overhead.
Because it relies purely on Vect2 and Rect2 structs, it is exceptionally fast (often running in microseconds), entirely zero-GC, and scales perfectly with the specific needs of your game.
CollisionHelper is designed for microsecond-level performance with zero garbage collection (zero-GC). Because it operates purely on stack-allocated structs (Vect2 and Rect2), there is no heap allocation, no boxing, and no virtual dispatch.
| Feature | Benefit |
|---|---|
| Static methods | No instance lookup, direct call |
| Struct parameters | No heap allocation, stack only |
| No state | No shared mutable data, thread-safe |
| No collections | No dictionary lookups, no list traversal |
| Inline-friendly | JIT can inline simple math operations |
| Zero-GC | No garbage collection pauses during gameplay |
| Operation | Approximate Time |
|---|---|
RectRect |
~0.001ms (1 microsecond) |
CircleCircle |
~0.001ms (1 microsecond) |
RectCircle |
~0.002ms (2 microseconds) |
PointRect |
~0.001ms (1 microsecond) |
DistanceRectRect |
~0.001ms (1 microsecond) |
RaycastRect |
~0.002ms (2 microseconds) |
SweptRectRect |
~0.005ms (5 microseconds) |
MoveAndSlideRect |
~0.01ms (10 microseconds) |
Note: Times are approximate and vary based on CPU. The key point is that these operations are measured in microseconds, not milliseconds.
| Approach | Memory Overhead | Update Cost | Collision Check |
|---|---|---|---|
| CollisionHelper (static) | None | None | ~0.001ms |
| CollisionManager (typical) | Lists, dictionaries, spatial grids | Rebuild spatial structures each frame | ~0.1ms (with lookups) |
The manager approach adds overhead for:
- Dictionary lookups (hash computation)
- Spatial grid updates (reinserting moving objects)
- Object indirection (pointer chasing)
- Cache misses (scattered heap allocations)
CollisionHelper eliminates all of this by doing pure math just stack structs and floating-point comparisons.
CollisionHelper does not provide:
- Automatic broadphase (spatial partitioning)
- Entity tracking
- Collision event callbacks
- Automatic resolution
Instead, it gives you building blocks to create these systems yourself, tailored to your game's specific needs. Many games don't need a full physics system. They just need to check if two things overlap, and CollisionHelper makes that check as fast as possible.
// Fast, simple, and only when you need it
if (CollisionHelper.RectRect(player, wall))
{
player.Position += CollisionHelper.PushRectRect(player, wall);
}Check if two rectangles overlap.
if (CollisionHelper.RectRect(player, wall))
{
// Player hit the wall
}Check if two circles overlap.
if (CollisionHelper.CircleCircle(playerPos, 16f, enemyPos, 20f))
{
// Player hit the enemy
}Check if a rectangle and a circle overlap.
if (CollisionHelper.RectCircle(wall, playerPos, 16f))
{
// Player circle hit the wall
}Check if a point is inside a rectangle or circle.
if (CollisionHelper.PointRect(mousePos, buttonRect))
{
// Mouse is over the button
}
if (CollisionHelper.PointCircle(mousePos, explosionCenter, 50f))
{
// Mouse is within explosion radius
}Check if a line segment intersects a rectangle or circle.
if (CollisionHelper.LineRect(start, end, wall))
{
// Line of sight is blocked by wall
}Distance checks are useful and proximity detection without doing full collision tests.
// Distance between two rectangles
float dist = CollisionHelper.DistanceRectRect(player, enemy);
// Distance between two circles
float dist = CollisionHelper.DistanceCircleCircle(playerPos, 16f, enemyPos, 20f);
// Distance between a rectangle and a circle
float dist = CollisionHelper.DistanceRectCircle(wall, playerPos, 16f);
// Check if enemy is within aggro range
if (CollisionHelper.DistanceCircleCircle(playerPos, 16f, enemyPos, 20f) < 100f)
{
// Enemy starts chasing
}Raycasts are useful for line-of-sight, aiming, shooting, and visibility checks.
// Cast a ray from player toward mouse
Vect2 direction = (mousePos - player.Center).Normalized();
if (CollisionHelper.RaycastRect(player.Center, direction, wall, out Vect2 hit, out float distance))
{
// Wall is in the way at 'hit' position
DrawLine(player.Center, hit, Color.Red);
}List<Rect2> walls = new();
List<(Vect2 center, float radius)> enemies = new();
if (CollisionHelper.RaycastAny(origin, direction, walls, enemies,
out Vect2 hit, out Vect2 normal, out float dist, out object hitObject))
{
// Hit something! hitObject tells you what it was
if (hitObject is Rect2) { /* Hit a wall */ }
if (hitObject is Vect2) { /* Hit an enemy */ }
}Swept collision prevents tunneling - when fast-moving objects pass through thin walls in a single frame.
// Fast-moving bullet
Rect2 bullet = new Rect2(100, 100, 4, 4);
Vect2 bulletVelocity = new Vect2(1000, 0);
if (CollisionHelper.SweptRectRect(bullet, bulletVelocity, wall,
out float timeOfImpact, out Vect2 hitPoint, out Vect2 hitNormal))
{
// Bullet will hit the wall at timeOfImpact (0-1)
// Move bullet to hitPoint and bounce/stop
}This works for:
-
SweptRectRect- Rectangle vs rectangle -
SweptCircleRect- Circle vs rectangle -
SweptCircleCircle- Circle vs circle
Normals tell you which direction a collision came from. Useful for bouncing, sliding, and pushing.
// Get the normal between overlapping shapes
Vect2 normal = CollisionHelper.GetCollisionNormal(player, wall);
// normal is (-1, 0) for left, (1, 0) for right, (0, -1) for top, (0, 1) for bottom
// Reflect velocity off the surface
Vect2 reflected = CollisionHelper.Reflect(velocity, normal, 0.8f);
// 80% bouncinessPushback resolves overlaps by pushing objects apart. This is essential for preventing objects from merging into each other.
if (CollisionHelper.RectRect(player, wall))
{
Vect2 push = CollisionHelper.PushRectRect(player, wall);
player.Position += push; // Push player out of the wall
}Pushback methods:
-
PushRectRect- Rect vs rect -
PushCircleRect- Circle vs rect -
PushCircleCircle- Circle vs circle
Move and slide lets you move an object and have it automatically slide along walls instead of stopping dead.
// Move player with slide along walls
Vect2 velocity = new Vect2(5, 0);
List<Rect2> obstacles = new List<Rect2> { wall, floor };
player.Position = CollisionHelper.MoveAndSlideRect(player, velocity, obstacles);Vect2 circlePos = new Vect2(150, 150);
float radius = 16f;
Vect2 velocity = new Vect2(5, 0);
List<Rect2> rectObstacles = new() { wall };
List<(Vect2 center, float radius)> circleObstacles = new()
{
(new Vect2(250, 250), 20f)
};
circlePos = CollisionHelper.MoveAndSlideCircle(
circlePos, radius, velocity, rectObstacles, circleObstacles);Check if one shape fully contains another.
// Is the player fully inside the safe zone?
if (CollisionHelper.RectContainsRect(safeZone, player))
{
// Player is safe!
}
// Is the circle fully inside the rectangle?
if (CollisionHelper.RectContainsCircle(rect, circleCenter, radius))
{
// Circle is fully contained
}Convert a circle to its bounding box (AABB) for broadphase optimization - skip expensive checks when objects are far apart.
// Get the bounding box of a circle
Rect2 circleBounds = CollisionHelper.GetCircleBounds(circlePos, 25f);
// Quick broadphase check
if (CollisionHelper.RectRect(circleBounds, wall))
{
// Now do the precise circle-rect check
if (CollisionHelper.RectCircle(wall, circlePos, 25f))
{
// Actually hit the wall
}
}Find the closest point on a shape to a given point.
// Closest point on a rectangle
Vect2 closest = CollisionHelper.ClosestPointRect(mousePos, buttonRect);
// Closest point on a circle
Vect2 closest = CollisionHelper.ClosestPointCircle(mousePos, explosionCenter, 50f);Bounce a velocity off a surface with optional bounciness.
// Bounce a ball off a wall
Vect2 normal = CollisionHelper.GetCollisionNormal(ball, wall);
ballVelocity = CollisionHelper.Reflect(ballVelocity, normal, 0.9f); // 90% bounceHere's a complete, runnable example showing a rectangle (player) moving and colliding with walls using MoveAndSlideRect. It defines input actions for WASD / Arrow keys and draws the results with PrimitiveBatcher.
using Void.Engine;
using Void.Engine.Helpers;
using Void.Engine.Graphics;
using Void.Engine.Inputs.InputActions;
using Void.Engine.Inputs.Keyboards;
using Void.Engine.Systems;
public sealed class CollisionDemo : Game
{
private const float Speed = 200f;
private readonly List<Rect2> _walls =
[
new Rect2(200, 100, 64, 128), // Wall
new Rect2(0, 400, 800, 32), // Floor
];
private Rect2 _player = new(100, 100, 32, 32);
private Vect2 _velocity = Vect2.Zero;
private PrimitiveBatcher _batcher;
private Camera _camera;
public CollisionDemo(GameSettings settings) : base(settings) { }
protected override void OnEnter()
{
// Define input actions
InputAction.AddAction("MoveLeft").AddKey(KeyboardKey.A).AddKey(KeyboardKey.Left);
InputAction.AddAction("MoveRight").AddKey(KeyboardKey.D).AddKey(KeyboardKey.Right);
InputAction.AddAction("MoveUp").AddKey(KeyboardKey.W).AddKey(KeyboardKey.Up);
InputAction.AddAction("MoveDown").AddKey(KeyboardKey.S).AddKey(KeyboardKey.Down);
// Initialize Camera and batcher
_camera = new Camera();
_batcher = new PrimitiveBatcher();
}
protected override void OnUpdate(FrameTime frameTime)
{
float dt = frameTime.DeltaTime;
var input = InputAction.GetState();
// Gather input
Vect2 move = Vect2.Zero;
if (input.IsPressed("MoveLeft")) move.X -= 1;
if (input.IsPressed("MoveRight")) move.X += 1;
if (input.IsPressed("MoveUp")) move.Y -= 1;
if (input.IsPressed("MoveDown")) move.Y += 1;
if (move.LengthSquared() > 0)
move = move.Normalized();
_velocity = move * Speed;
// Move and slide
_player.Position = CollisionHelper.MoveAndSlideRect(_player, _velocity * dt, _walls);
// Update Camera
_camera.Position = _player.Position + _player.Size / 2;
}
protected override void OnDraw(FrameTime frameTime)
{
_batcher.Begin(SortMode.Immediate, camera: _camera);
// Draw walls
foreach (var wall in _walls)
_batcher.DrawRect(wall.Position, wall.Size, Color.Red);
// Draw player
_batcher.DrawRect(_player.Position, _player.Size, Color.Blue);
_batcher.End();
}
protected override void OnExit()
{
_batcher.Dispose();
}
}| Category | What It Does |
|---|---|
| Detection | Check if shapes overlap (Rect, Circle, Point, Line) |
| Distance | Measure distance between shapes |
| Raycast | Cast rays against shapes |
| Swept Collision | Prevent tunneling for fast-moving objects |
| Normals | Get collision direction |
| Pushback | Resolve overlaps |
| Move & Slide | Slide along walls |
| Containment | Check if one shape contains another |
| Bounds Conversion | Get AABB for broadphase |
| Closest Point | Find nearest point on a shape |
| Reflection | Bounce velocities off surfaces |
For camera behavior used in the complete example, see Camera.
Home · Getting Started · Rendering · Custom Renderers · GitHub · Report an Issue
Built with VOID Engine · MIT License
- Coroutines
- State Machine
- Save System
- Pathfinding
- Logging
- Beacon Manager
- Beacon Event System
- Discoverable System
- Instance Helper
- BeaconManager Extensions
- BeaconHandle Extensions
- Enum Extensions
- String Extensions
- Int Extensions
- Float Extensions
- IEnumerable Extensions
- Random Extensions
- Sound Extensions
- Font Extensions