How to determine whether two axis‑aligned rectangles overlap in Swift

1 Answer

0 votes
/*
Axis‑aligned rectangles are simply rectangles whose edges are parallel to the 
coordinate axes — meaning their sides are horizontal and vertical. 
That single assumption makes the overlap test dramatically simpler and faster.
*/

/*
    Rectangle overlap detection (axis-aligned)

    Each rectangle is defined by:
        - x, y : coordinates of its top-left corner
        - w, h : width and height

    Two rectangles DO NOT overlap if any separating condition is true:
        - One is completely to the left of the other
        - One is completely to the right of the other
        - One is completely above the other
        - One is completely below the other

    Otherwise, they overlap.

    This is the standard O(1) test for axis-aligned rectangles.
*/

struct Rect {
    var x: Double    // top-left X
    var y: Double    // top-left Y
    var w: Double    // width
    var h: Double    // height
}

/*
    Returns true if rectangles A and B overlap.
*/
func rectanglesOverlap(_ A: Rect, _ B: Rect) -> Bool {
    // Compute edges of A
    let A_left: Double   = A.x
    let A_right: Double  = A.x + A.w
    let A_top: Double    = A.y
    let A_bottom: Double = A.y + A.h

    // Compute edges of B
    let B_left: Double   = B.x
    let B_right: Double  = B.x + B.w
    let B_top: Double    = B.y
    let B_bottom: Double = B.y + B.h

    // Separating conditions:
    if A_right <= B_left { return false }   // A is left of B
    if B_right <= A_left { return false }   // B is left of A
    if A_bottom <= B_top { return false }   // A is above B
    if B_bottom <= A_top { return false }   // B is above A

    return true // Otherwise, they overlap
}

let A = Rect(x: 10, y: 10, w: 30, h: 20)   // Example rectangle A
let B = Rect(x: 25, y: 15, w: 40, h: 25)   // Overlaps A
let C = Rect(x: 100, y: 100, w: 10, h: 10) // Does not overlap A

print("A vs B overlap? \(rectanglesOverlap(A, B) ? "YES" : "NO")")
print("A vs C overlap? \(rectanglesOverlap(A, C) ? "YES" : "NO")")



/*
run:

A vs B overlap? YES
A vs C overlap? NO

*/

 



answered Jul 18 by avibootz

Related questions

...