Repository navigation
Collision Move System
Marko Koschak edited this page Oct 25, 2026
·
1 revision
The CollisionMoveSystem is a 2D tile-grid collision detection and resolution system built for platformer physics in korge-fleks. It handles sub-sampled collision checks against worldMapData static grid tiles at a fixed rate of 60 Hz (Fixed(1 / 60f)).
- Integrated Displacement Sub-Stepping: Divides total frame movement into sub-steps smaller than or equal to the tile size to prevent tunneling through level geometry.
- Sequential Axis Probing: Probes and resolves horizontal collision first, then probes and resolves vertical collision using updated positions.
-
Surface Reaction Handling: Applies configurable reactions (
GROUND_WALKING,EXPLOSION_SLIDING,BOUNCE) to velocity on collision impact. -
Partial Impact Displacement (
calculateRatio): Calculates partial displacement for non-colliding axes based on the fraction of the sub-step completed before impact. - Playfield Boundary Clamping: Clamps positions to map boundaries with a 16px guard margin.
-
PositionComponent(Position): World coordinates (x,y) and offsets (offsetX,offsetY). -
MotionComponent(Motion): Velocity (velocityX,velocityY) and surface reaction modes (surfaceReactionX,surfaceReactionY). -
CollisionComponent(Collision): Rectangular bounding box (rect) and directional collision flags (right,left,isGrounded,isCollidingAbove). -
GravityComponent(Optional): Applies delta gravity tovelocityY. -
DebugCollisionShapesComponent(Optional): Visualizes probe points and grid cell checks.
For each entity with PositionComponent, MotionComponent, and CollisionComponent:
┌───────────────────────────────────────────────────────────┐
│ Apply Gravity (if GravityComponent present) │
└─────────────────────────────┬─────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────┐
│ Calculate Frame Movement (overallMovementX, Y) │
│ Determine Sub-Step Count via getCollisionSteps() │
└─────────────────────────────┬─────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────┐
│ Reset Directional Flags (right, left, grounded, above) │
│ Execute processCollisionSteps() -> checkCollision() │
└─────────────────────────────┬─────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────┐
│ Zero out small residual velocities (< 0.0005f) │
│ Clamp position in playfield (checkPlayfieldBoundaries) │
└───────────────────────────────────────────────────────────┘
-
Gravity Application: If
GravityComponentis present,motionComponent.velocityYis updated bycalculateDeltaGravity() * deltaTime. -
Displacement & Sub-Stepping:
overallMovementX = velocityX * deltaTimeoverallMovementY = velocityY * deltaTimestepSize = min(min(rect.width, rect.height), gridSize)- Calculates
steps = getCollisionSteps(overallMovementX, overallMovementY, stepSize).
-
Flag Reset: Resets
right,left,isGrounded, andisCollidingAbovewhensteps > 0. -
Sub-Step Execution: Calls
processCollisionSteps(...), executingcheckCollision(...)for each sub-step slice. -
Velocity Thresholding: Zeroes out micro-velocities less than
0.0005f. -
Boundary Clamping: Invokes
checkPlayfieldBoundaries(positionComponent)to enforce map edges.
protected fun checkCollision(
xMovement: Float,
yMovement: Float,
positionComponent: Position,
motionComponent: Motion,
collisionComponent: Collision,
gridSize: Float,
debugShapesComponent: DebugCollisionShapes?
): Boolean-
Purpose: Orchestrates two-phase horizontal and vertical probing and resolution for a single sub-step displacement (
xMovement,yMovement). -
Workflow:
-
Phase 1: Horizontal Probe & Resolution:
- Computes initial and moved leading edge coordinates (
xPosMovedLeadingEdge). - Calls
probeCollisionHorizontally(...). - If colliding: calls
resolveCollisionHorizontally(...)(snapping$x$ ). - If not colliding: adds
xMovementdirectly topositionComponent.x.
- Computes initial and moved leading edge coordinates (
-
Phase 2: Vertical Probe & Resolution:
- Recomputes moved vertical bounds (
yPosMovedLeadingEdge) using the updated$x$ position. - Calls
probeCollisionVertically(...). - If colliding:
- Calls
resolveCollisionVertically(...)(snapping$y$ ). - If
surfaceReactionX != GROUND_WALKING: calculates impact ratioyRatioviacalculateRatio(...)and updatespositionComponent.x = xPositionSaved + xMovement * yRatio.
- Calls
- If not colliding:
- If horizontal collision occurred in Phase 1 and
surfaceReactionY != GROUND_WALKING: calculatesxRatioand applies partial$y$ movementyDeltaMove = yMovement * xRatio. - Otherwise: adds
yMovementdirectly topositionComponent.y.
- If horizontal collision occurred in Phase 1 and
- Recomputes moved vertical bounds (
-
Phase 1: Horizontal Probe & Resolution:
-
Return Value: Returns
trueif either horizontal or vertical collision occurred.
protected fun calculateRatio(
movement: Float,
posInitialLeadingEdge: Float,
posMovedLeadingEdge: Float,
gridSize: Float
): Float-
Purpose: Calculates the fractional entry ratio (
$ratio \in [0..1]$ ) traversed along an axis before the leading edge hits a target cell boundary. -
Math:
-
Rightward / Downward (
movement > 0f):$$xDistance = \text{cellMovedLeadingEdge} \times \text{gridSize} - \text{posInitialLeadingEdge}$$ $$ratio = \frac{xDistance}{movement}$$ -
Leftward / Upward (
movement < 0f):$$xDistance = (\text{cellMovedLeadingEdge} + 1) \times \text{gridSize} - \text{posInitialLeadingEdge}$$ $$ratio = \frac{xDistance}{movement}$$
-
Rightward / Downward (
-
Return Value: Fractional ratio float in
$[0..1]$ , or0fifmovementis zero.
protected fun probeCollisionHorizontally(
xMovement: Float,
yMovement: Float,
yPosTop: Float,
yPosBottom: Float,
xPosMovedLeadingEdge: Float,
verticalSteps: Int,
gridSize: Float,
debugShapesComponent: DebugCollisionShapes?
): Boolean-
Purpose: Probes the leading vertical edge (
$xPosMovedLeadingEdge$ ) acrossverticalStepssample points along the$Y$ -axis. -
Sampling Order:
- If
yMovement < 0f(moving up): samples from bottom ($yPosBottom$ ) to top ($yPosTop$ ). - If
yMovement >= 0f(moving down/stationary): samples from top ($yPosTop$ ) to bottom ($yPosBottom$ ).
- If
-
Tile Check: Checks
worldMapData.hasCollision(cxProbe, cyProbe)for each sample point. -
Return Value:
trueif any probed point touches a solid level tile;falseotherwise.
protected fun probeCollisionVertically(
xMovement: Float,
yMovement: Float,
xPosMovedLeft: Float,
xPosMovedRight: Float,
yPosMovedLeadingEdge: Float,
horizontalSteps: Int,
gridSize: Float,
debugShapesComponent: DebugCollisionShapes?
): Boolean-
Purpose: Probes the leading horizontal edge (
$yPosMovedLeadingEdge$ ) acrosshorizontalStepssample points along the$X$ -axis. -
Sampling Order:
- If
xMovement < 0f(moving left): samples from right ($xPosMovedRight$ ) to left ($xPosMovedLeft$ ). - If
xMovement >= 0f(moving right/stationary): samples from left ($xPosMovedLeft$ ) to right ($xPosMovedRight$ ).
- If
-
Tile Check: Checks
worldMapData.hasCollision(cxProbe, cyProbe)for each sample point. -
Return Value:
trueif any probed point touches a solid level tile;falseotherwise.
protected fun resolveCollisionHorizontally(
xMovement: Float,
xPosMovedLeadingEdge: Float,
positionComponent: Position,
motionComponent: Motion,
collisionComponent: Collision,
gridSize: Float
)-
Purpose: Resolves horizontal collision by adjusting
$v_x$ , snapping$x$ outside the colliding tile, and updating flags. -
Surface Reactions (
surfaceReactionX):-
GROUND_WALKING: SetsvelocityX = 0f(retainsvelocityY). -
EXPLOSION_SLIDING: MultipliesvelocityX *= 0.07fandvelocityY *= 0.1f(allows explosions to slide into/along walls). -
BOUNCE: Inverts velocityvelocityX *= -1f.
-
-
Position Snapping:
-
Moving Right (
xMovement > 0f):$$\text{positionComponent.x} = \text{cxCell} \times \text{gridSize} - \text{guardMove} - \text{collisionRectOffsetX}$$ SetscollisionComponent.right = true. -
Moving Left (
xMovement < 0f):$$\text{positionComponent.x} = (\text{cxCell} + 1) \times \text{gridSize} + \text{guardMove} + \text{collisionRectOffsetX}$$ SetscollisionComponent.left = true.
-
Moving Right (
protected fun resolveCollisionVertically(
yMovement: Float,
yPosMovedLeadingEdge: Float,
positionComponent: Position,
motionComponent: Motion,
collisionComponent: Collision,
gridSize: Float
)-
Purpose: Resolves vertical collision by adjusting
$v_y$ , snapping$y$ outside the colliding tile, and updating flags. -
Surface Reactions (
surfaceReactionY):-
GROUND_WALKING: SetsvelocityY = 0f(retainsvelocityX). -
EXPLOSION_SLIDING: MultipliesvelocityX *= 0.1fandvelocityY *= 0.07f. -
BOUNCE: Inverts velocityvelocityY *= -1f.
-
-
Position Snapping:
-
Moving Down (
yMovement > 0f):$$\text{positionComponent.y} = \text{cyCell} \times \text{gridSize} - \text{guardMove} - \text{collisionRectOffsetY}$$ SetscollisionComponent.isGrounded = true. -
Moving Up (
yMovement < 0f):$$\text{positionComponent.y} = (\text{cyCell} + 1) \times \text{gridSize} + \text{guardMove} + \text{collisionRectOffsetY}$$ SetscollisionComponent.isCollidingAbove = true.
-
Moving Down (
protected fun getCollisionSteps(
horizontalMovement: Float,
verticalMovement: Float,
gridSize: Float
): Int-
Purpose: Calculates the number of sub-step iterations required for frame displacement (
horizontalMovement,verticalMovement). -
Formula:
$$\text{steps} = \left\lceil \frac{\max(|dx|, |dy|)}{\text{gridSize}} \right\rceil$$ -
Guard Safeguards:
- Returns
0ifgridSizeis almost zero ($< 1\text{px}$ ). - Clamps maximum step count to
100to prevent infinite loops during extreme velocities.
- Returns
protected fun processCollisionSteps(
steps: Int,
overallMovementX: Float,
overallMovementY: Float,
callback: (movementX: Float, movementY: Float) -> Boolean
)-
Purpose: Divides total displacement into
stepsuniform slices (movementX = overallMovementX / steps,movementY = overallMovementY / steps) and passes each sub-step delta tocallback. -
Early Termination: Stops sub-stepping loop immediately if
callbackreturnstrue(e.g. for projectiles or triggers).
protected fun checkPlayfieldBoundaries(positionComponent: Position)-
Purpose: Ensures entity position remains strictly within map boundary limits (
guardBorder = worldMapData.tileSize.toFloat()). -
Clamping Rules:
$x + \text{offsetX} \le \text{guardBorder} \implies x = \text{guardBorder} - \text{offsetX}$ $x + \text{offsetX} \ge \text{worldWidth} - \text{guardBorder} \implies x = \text{worldWidth} - \text{guardBorder} - \text{offsetX}$ $y + \text{offsetY} > \text{worldHeight} - \text{guardBorder} \implies y = \text{worldHeight} - \text{guardBorder} - \text{offsetY}$
protected fun Float.isNotAlmostZero(): Boolean = this.absoluteValue > guard-
Purpose: Helper extension function to test if a floating point value exceeds the deadzone threshold (
guard = 0.01f).
| Mode | Reaction on |
Reaction on |
Typical Use Case |
|---|---|---|---|
GROUND_WALKING |
|
|
Player characters, enemies, walking NPCs |
EXPLOSION_SLIDING |
|
|
Explosions, debris particles sliding into walls/floors |
BOUNCE |
Bouncy grenades, rubber balls, springs |
Korge-fleks framework by jobe-m is based on Korge Game Engine and Fleks Entity Component System