Skip to main content

rectangles_intersect

Function rectangles_intersect 

Source
pub fn rectangles_intersect(a: &Rect, b: &Rect) -> bool
Expand description

Rectangle intersection algorithm using the Separating Axis Theorem.

§Theory

The Separating Axis Theorem states that two convex polygons intersect if and only if there is no separating axis between them. For axis-aligned rectangles, we only need to check the X and Y axes.

§Algorithm

Two rectangles A and B intersect if and only if:

  • They overlap on the X-axis AND
  • They overlap on the Y-axis

They DON’T overlap on an axis if:

  • A is completely to one side of B on that axis

§Complexity

  • Time: O(1) - exactly 4 comparisons
  • Space: O(1) - no additional memory

§References

  • “Real-Time Collision Detection” by Christer Ericson, Chapter 4
  • “Computational Geometry: Algorithms and Applications” by de Berg et al.

§Examples

use hojicha_rendering::algorithms::rectangles_intersect;
use ratatui::layout::Rect;

let a = Rect::new(0, 0, 10, 10);
let b = Rect::new(5, 5, 10, 10);  // overlapping
let c = Rect::new(20, 20, 10, 10); // separate

assert!(rectangles_intersect(&a, &b));
assert!(!rectangles_intersect(&a, &c));