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

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 {
    x: f64,      // top-left X
    y: f64,      // top-left Y
    w: f64,      // width
    h: f64,      // height
}

/*
    Returns true if rectangles A and B overlap.
*/
fn rectangles_overlap(a: &Rect, b: &Rect) -> bool {
    // Compute edges of A
    let a_left: f64   = a.x;
    let a_right: f64  = a.x + a.w;
    let a_top: f64    = a.y;
    let a_bottom: f64 = a.y + a.h;

    // Compute edges of B
    let b_left: f64   = b.x;
    let b_right: f64  = b.x + b.w;
    let b_top: f64    = b.y;
    let b_bottom: f64 = 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

    true // Otherwise, they overlap
}

fn main() {
    let a = Rect { x: 10.0, y: 10.0, w: 30.0, h: 20.0 };   // Example rectangle A
    let b = Rect { x: 25.0, y: 15.0, w: 40.0, h: 25.0 };   // Overlaps A
    let c = Rect { x: 100.0, y: 100.0, w: 10.0, h: 10.0 }; // Does not overlap A

    println!("A vs B overlap? {}", if rectangles_overlap(&a, &b) { "YES" } else { "NO" });
    println!("A vs C overlap? {}", if rectangles_overlap(&a, &c) { "YES" } else { "NO" });
}



/*
run:

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

*/

 



answered Jul 18 by avibootz

Related questions

...