Skip to content

Collision Move System

Marko Koschak edited this page Oct 25, 2026 · 1 revision

CollisionMoveSystem Technical Specification & Sub-Function Guide

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


1. System Overview & Architecture

Primary Responsibilities

  1. 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.
  2. Sequential Axis Probing: Probes and resolves horizontal collision first, then probes and resolves vertical collision using updated positions.
  3. Surface Reaction Handling: Applies configurable reactions (GROUND_WALKING, EXPLOSION_SLIDING, BOUNCE) to velocity on collision impact.
  4. Partial Impact Displacement (calculateRatio): Calculates partial displacement for non-colliding axes based on the fraction of the sub-step completed before impact.
  5. Playfield Boundary Clamping: Clamps positions to map boundaries with a 16px guard margin.

Component Dependencies

  • 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 to velocityY.
  • DebugCollisionShapesComponent (Optional): Visualizes probe points and grid cell checks.

2. Core Lifecycle: onTickEntity(entity)

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)    │
└───────────────────────────────────────────────────────────┘
  1. Gravity Application: If GravityComponent is present, motionComponent.velocityY is updated by calculateDeltaGravity() * deltaTime.
  2. Displacement & Sub-Stepping:
    • overallMovementX = velocityX * deltaTime
    • overallMovementY = velocityY * deltaTime
    • stepSize = min(min(rect.width, rect.height), gridSize)
    • Calculates steps = getCollisionSteps(overallMovementX, overallMovementY, stepSize).
  3. Flag Reset: Resets right, left, isGrounded, and isCollidingAbove when steps > 0.
  4. Sub-Step Execution: Calls processCollisionSteps(...), executing checkCollision(...) for each sub-step slice.
  5. Velocity Thresholding: Zeroes out micro-velocities less than 0.0005f.
  6. Boundary Clamping: Invokes checkPlayfieldBoundaries(positionComponent) to enforce map edges.

3. Detailed Sub-Function Breakdown

checkCollision

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:
    1. 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 xMovement directly to positionComponent.x.
    2. 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 ratio yRatio via calculateRatio(...) and updates positionComponent.x = xPositionSaved + xMovement * yRatio.
      • If not colliding:
        • If horizontal collision occurred in Phase 1 and surfaceReactionY != GROUND_WALKING: calculates xRatio and applies partial $y$ movement yDeltaMove = yMovement * xRatio.
        • Otherwise: adds yMovement directly to positionComponent.y.
  • Return Value: Returns true if either horizontal or vertical collision occurred.

calculateRatio

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}$$
  • Return Value: Fractional ratio float in $[0..1]$, or 0f if movement is zero.

probeCollisionHorizontally

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$) across verticalSteps sample 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$).
  • Tile Check: Checks worldMapData.hasCollision(cxProbe, cyProbe) for each sample point.
  • Return Value: true if any probed point touches a solid level tile; false otherwise.

probeCollisionVertically

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$) across horizontalSteps sample 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$).
  • Tile Check: Checks worldMapData.hasCollision(cxProbe, cyProbe) for each sample point.
  • Return Value: true if any probed point touches a solid level tile; false otherwise.

resolveCollisionHorizontally

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: Sets velocityX = 0f (retains velocityY).
    • EXPLOSION_SLIDING: Multiplies velocityX *= 0.07f and velocityY *= 0.1f (allows explosions to slide into/along walls).
    • BOUNCE: Inverts velocity velocityX *= -1f.
  • Position Snapping:
    • Moving Right (xMovement > 0f): $$\text{positionComponent.x} = \text{cxCell} \times \text{gridSize} - \text{guardMove} - \text{collisionRectOffsetX}$$ Sets collisionComponent.right = true.
    • Moving Left (xMovement < 0f): $$\text{positionComponent.x} = (\text{cxCell} + 1) \times \text{gridSize} + \text{guardMove} + \text{collisionRectOffsetX}$$ Sets collisionComponent.left = true.

resolveCollisionVertically

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: Sets velocityY = 0f (retains velocityX).
    • EXPLOSION_SLIDING: Multiplies velocityX *= 0.1f and velocityY *= 0.07f.
    • BOUNCE: Inverts velocity velocityY *= -1f.
  • Position Snapping:
    • Moving Down (yMovement > 0f): $$\text{positionComponent.y} = \text{cyCell} \times \text{gridSize} - \text{guardMove} - \text{collisionRectOffsetY}$$ Sets collisionComponent.isGrounded = true.
    • Moving Up (yMovement < 0f): $$\text{positionComponent.y} = (\text{cyCell} + 1) \times \text{gridSize} + \text{guardMove} + \text{collisionRectOffsetY}$$ Sets collisionComponent.isCollidingAbove = true.

getCollisionSteps

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 0 if gridSize is almost zero ($&lt; 1\text{px}$).
    • Clamps maximum step count to 100 to prevent infinite loops during extreme velocities.

processCollisionSteps

protected fun processCollisionSteps(
    steps: Int,
    overallMovementX: Float,
    overallMovementY: Float,
    callback: (movementX: Float, movementY: Float) -> Boolean
)
  • Purpose: Divides total displacement into steps uniform slices (movementX = overallMovementX / steps, movementY = overallMovementY / steps) and passes each sub-step delta to callback.
  • Early Termination: Stops sub-stepping loop immediately if callback returns true (e.g. for projectiles or triggers).

checkPlayfieldBoundaries

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} &gt; \text{worldHeight} - \text{guardBorder} \implies y = \text{worldHeight} - \text{guardBorder} - \text{offsetY}$

Float.isNotAlmostZero()

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

4. Surface Reaction Modes Summary

Mode Reaction on $X$ Impact Reaction on $Y$ Impact Typical Use Case
GROUND_WALKING $v_x = 0$, $v_y$ unchanged $v_y = 0$, $v_x$ unchanged Player characters, enemies, walking NPCs
EXPLOSION_SLIDING $v_x *= 0.07$, $v_y *= 0.1$ $v_x *= 0.1$, $v_y *= 0.07$ Explosions, debris particles sliding into walls/floors
BOUNCE $v_x *= -1.0$ $v_y *= -1.0$ Bouncy grenades, rubber balls, springs

Clone this wiki locally