The engine currently only supports AABB collision via BoxCollider. The goal is to
add arbitrary convex polygon collision support so entities can have triangular, hexagonal,
or any convex shape as colliders — enabling sloped surfaces, angled walls, irregular
platforms, etc.
javidx9's implementation demonstrates two approaches: SAT and Diagonals. After analysis,
SAT (Separating Axis Theorem) is the clear best fit for this engine.
Algorithm Choice: SAT
Criterion
SAT
Diagonals (javidx9)
GJK/EPA
Contact normal quality
Excellent (directly from MTV)
Decent (perpendicular to intersected edge)
Excellent (EPA second pass)
Penetration depth
Directly computed (min overlap)
Requires extra work
Computed by EPA
Performance (2D convex)
Good; early-exit on separating axis
O(n*m) diagonal-edge tests
Two-phase overhead
AABB as special case
Trivial (4 vertices, 2 unique normals)
Not natural
Possible but complex
Implementation complexity
Moderate
Moderate
High
SAT wins because it directly produces the Minimum Translation Vector (MTV) — both
the direction (ContactNormal) and magnitude (PenetrationDepth) needed for resolution.
GJK/EPA is overkill for 2D convex shapes. The Diagonals method doesn't directly give
penetration depth.
Swept vs discrete: The current AABB system uses swept detection (Minkowski + raycast)
which prevents tunneling at high speeds. SAT is inherently discrete (detects current-frame
overlap, not time-of-impact). Strategy:
Any polygon pair: discrete SAT with broad-phase AABB rejection
Tunneling mitigation for polygon collisions can be added later (swept SAT or sub-stepping)
Implementation Plan
Phase 1: SAT math utility + ConvexCollider component
New file: MonoDreams/Extensions/Monogame/SATCollision.cs
Static helper class (same pattern as CollisionRect) with:
Assistant
I'll start by reading all the key files I need to understand before implementing. Let me gather context in parallel.
Assistant
Let me also check a few more files for complete context.
Assistant
Good, I have all the context I need. Let me also quickly check one more thing before starting.
Assistant
Build is clean (0 errors). Now let me set up task tracking and start implementing.
Assistant
Starting with Phase 1. Let me create the SAT math utility.
Assistant
Now the ConvexCollider component.
Assistant
Now the ColliderTag, message updates, and delegate update.
Assistant
Now add PenetrationDepth to the collision message interface and record.
Assistant
Now update the delegate to include penetrationDepth.
Assistant
I need to add penetrationDepth to the delegate. Let me check how it's instantiated.
Assistant
Let me check the factory functions used.
Assistant
I need to update the delegate to include penetrationDepth and update all callers. Let me do all these edits.
Assistant
Now update GameCollisionHelper to match the new delegate signature.
Assistant
Now update CreateRunnerCollision in InfiniteRunnerScreen.
Assistant
Now the big one — refactoring the detection system. This needs to:
Subscribe to EntityComponentAdded for both collider types to auto-tag with ColliderTag
Query With<ColliderTag>().With<Transform>()
Dispatch based on collider pair type
Transform ConvexCollider.WorldVertices before testing
Assistant
Now the resolution system — needs to handle both collider types.
Assistant
Now update the debug system to also handle ConvexCollider entities.
Assistant
I see the debug system uses event subscriptions to add debug visuals when a component is added. I'll add a subscription for ConvexCollider too. Since ConvexCollider doesn't have Rectangle bounds, I'll compute the AABB from model vertices for the debug bounding box (a reasonable approximation for the debug overlay).
Assistant
Let me do a build check before writing tests.
Assistant
Two issues: stackalloc span escape and Point/Vector2 type mismatch. Let me fix both.
Assistant
Now fix the resolution system's same stackalloc issue.
Assistant
Now fix the debug system Point→Vector2 issue. Let me check what type Size and Offset expect.
Assistant
Size and Offset are Vector2, not Point. Let me fix the debug system.
Assistant
I also need to update BoxToPolygon to accept Span<Vector2> since I'm now passing arrays. Let me check the current signature — it already takes Span<Vector2> which is fine since arrays implicitly convert to spans. But I also need to check the SATCollision.BoxToPolygon — I used Span<Vector2> output parameter, and passing a Vector2[] should work fine.
Assistant
Build is clean — 0 errors. Now let me write the unit tests.
Assistant
All 25 tests pass (including the 20 new SAT tests + 5 existing integration tests). Build is clean with 0 errors.
Assistant
Here's a summary of everything implemented:
What was done
New files created (4)
MonoDreams/Extensions/Monogame/SATCollision.cs — Static SAT helper with PolygonVsPolygon, ProjectPolygon, PolygonCenter, BoxToPolygon, and ComputeAABB
MonoDreams/Component/Collision/ConvexCollider.cs — Polygon collider component with , , , and
PolygonVsPolygon(ReadOnlySpan<Vector2> polyA, ReadOnlySpan<Vector2> polyB, out Vector2 normal, out float depth) — core SAT
ProjectPolygon(ReadOnlySpan<Vector2>, Vector2 axis, out float min, out float max) — vertex projection
PolygonCenter(ReadOnlySpan<Vector2>) — centroid for normal direction correction
BoxToPolygon(BoxCollider, Transform) — convert AABB to 4-vertex polygon for mixed-type tests
New file: MonoDreams/Component/Collision/ConvexCollider.cs
code
class ConvexCollider : ICollider
Vector2[] ModelVertices — local-space vertices (clockwise winding)
Vector2[] WorldVertices — pre-allocated, updated each frame by detection system
CollisionRect BroadPhaseAABB — computed from WorldVertices min/max for fast rejection
HashSet<int> ActiveLayers, bool Passive, bool Enabled — same as BoxCollider
Why a new component instead of extending BoxCollider: the data models are fundamentally
different (Rectangle vs Vector2[]). A union would leave fields unused and violate the
"pure data container" principle. Both share ICollider — that's the right abstraction.
Add PenetrationDepth to collision messages:
Add float PenetrationDepth to ICollisionMessage and CollisionMessage
Defaults to 0 for swept AABB collisions (where ContactTime is the primary metric)
New file: MonoDreams/Component/Collision/ColliderTag.cs — empty struct tag.
In the detection system constructor, subscribe to EntityComponentAdded<BoxCollider> and
EntityComponentAdded<ConvexCollider> to auto-set ColliderTag. This means zero changes
to existing entity factories — any entity that gets a BoxCollider automatically gets the
tag.
Detection system refactored to:
Query With<ColliderTag>().With<Transform>()
Filter active/non-passive in Update (since the predicate query can't span both types)
GetCollider(entity) helper: checks Has<BoxCollider> then Has<ConvexCollider>
Currently hardcoded to BoxCollider + DynamicRectVsRect re-validation. Needs to handle
both collider types.
Resolution logic changes:
Re-validation: dispatch based on collider pair (same as detection). For Box-vs-Box,
re-run DynamicRectVsRect (unchanged). For polygon pairs, re-run SAT with current
positions.
Position correction: for polygon collisions, push by
contactNormal * penetrationDepth instead of axis-aligned snap-to-contact-point.
Velocity damping: project velocity onto collision normal and remove that component:
velocity -= dot(velocity, normal) * normal (only if moving into collision).
RigidBodyTouchMessage: derive side from ContactNormal direction
(predominant axis → Top/Bottom/Left/Right).
Phase 4: Debug rendering
Modify: MonoDreams/System/Draw/ColliderDebugSystem.cs (if it exists) or add polygon
outline rendering. For ConvexCollider, draw line segments between consecutive
WorldVertices.
Phase 5: Tests
New file: MonoDreams.Tests/Collision/SATCollisionTests.cs
Unit tests:
Two separated squares → no collision
Two overlapping squares → correct MTV direction and depth
Triangle vs square (overlapping and separated)
Rotated rectangle vs axis-aligned rectangle
Box-to-polygon conversion matches AABB intersection result
Containment case (one polygon fully inside another)
Edge-touching (zero penetration boundary)
Integration test:
Entity with ConvexCollider collides correctly with BoxCollider entity in game loop
Files to Create
MonoDreams/Extensions/Monogame/SATCollision.cs — SAT algorithm
BoxCollider.cs, ICollider.cs, CollisionRect.cs — no modifications needed
TransformPhysicalCollisionResolutionSystem.cs — inherits from base, no changes
TransformVelocitySystem.cs, TransformCommitSystem.cs — pipeline stays the same
All entity factories — ColliderTag auto-applied via subscription
Out of Scope (future work)
Blender exporter for polygon collision vertices
Swept SAT (time-of-impact for polygon pairs)
Concave shape decomposition
Spatial partitioning (quad-tree broad phase)
Verification
dotnet build — ensure no compilation errors
dotnet test MonoDreams.Tests/ — SAT unit tests pass
Manual test: create a triangle ConvexCollider entity in the example game, verify it
collides correctly with existing BoxCollider walls/platforms
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /Users/rodrigooliveira/.REDACTED.jsonl
ModelVertices
WorldVertices
BroadPhaseAABB
UpdateWorldVertices(Transform)
MonoDreams/Component/Collision/ColliderTag.cs — Empty marker struct auto-applied when any collider is added
MonoDreams.Tests/Collision/SATCollisionTests.cs — 20 unit tests covering separation, overlap, MTV, triangle vs square, rotated shapes, box conversion, containment, edge touching, pentagon, world vertex transform with rotation/scale
TransformCollisionDetectionSystem.cs — Full rewrite: auto-tags ColliderTag via subscriptions, queries by tag, dispatches Box-vs-Box (unchanged swept AABB) or SAT (with broad-phase AABB rejection) based on collider pair type
TransformCollisionResolutionSystem.cs — Split into ResolveBoxVsBox (unchanged) and ResolveSAT (MTV push + velocity damping + normal-to-side mapping)
ColliderDebugSystem.cs — Added ConvexCollider subscription with AABB-based debug outline
GameCollisionHelper.cs + InfiniteRunnerScreen.cs — Updated to match new delegate signature
Key design decisions
Zero regression: Box-vs-Box path is completely unchanged (swept AABB)
SAT for polygon pairs: Produces MTV directly (normal + depth), broad-phase AABB rejects cheap
ColliderTag auto-tagging: Entity factories need zero changes — subscribing to EntityComponentAdded handles it
Reusable array buffers instead of stackalloc to avoid C# span escape restrictions