Bounding Box Collision (The Quick Check)
Collision detection is computationally expensive. The fastest method is the Bounding Box check. This method checks if the rectangular area occupied by two objects (their boxes) overlap on the X and Y axes. If the boxes don’t overlap, the objects cannot be touching.
The Principle: An overlap exists if:
- Object A’s right edge (
A.X + A.Width
) is > Object B’s left edge (B.X
), AND - Object A’s left edge (
A.X
) is < Object B’s right edge (B.X + B.Width
), AND - The same two conditions are met for the Y-axis.
Z80 Implementation (X-Axis Check):
; Check 1: Is A's right edge beyond B's left edge? (A.X + A.W > B.X)
LD HL, A_RIGHT_X ; HL = A.X + A.Width
LD DE, B_LEFT_X ; DE = B.X
OR A ; Clear Carry flag
SBC HL, DE ; Subtract B.X from A.Right.
JP C, NO_COLLISION_X ; If Carry is set (borrow needed), then A.Right < B.X. No overlap!
; ... (Perform Check 2: A.X < B.Right)
Pixel-Perfect Collision (The Bitwise Check)
If the bounding boxes overlap, a pixel-perfect check is necessary to confirm the objects are truly touching (not just their empty space). This is done by checking the screen data itself.
The Method:
- Read the screen byte where the two objects overlap (
BYTE_A
andBYTE_B
). - Apply a bitwise
AND
operation on the two bytes:A ← BYTE_A AND BYTE_B
. - If the result in the Accumulator (A) is non-zero, at least one common bit (pixel) is set, meaning a collision has occurred!
Z80 Implementation:
; Assume HL points to the overlap byte for Object A, and DE for Object B
; Step 1: Get the two overlapping bytes
LD A, (HL) ; A = BYTE_A
LD B, (DE) ; B = BYTE_B
; Step 2: Bitwise AND
AND B ; A ← A AND B
; Step 3: Check the result (if A ≠ 0, collision occurred)
OR A ; Set flags based on A (efficient way to test if A=0)
JP NZ, COLLISION_TRUE ; Jump if result is Not Zero