13 Rectangle Collision Detection
This section covers rectangle creation and collision detection using both integer-based (SDL_Rect) and floating-point (SDL_FRect) rectangles.
13.1 Creating Rectangles
Values are truncated to integers.
(define player-hitbox (make-rect 100 200 32 32))
procedure
(make-frect x y w h) → SDL_FRect?
x : real? y : real? w : real? h : real?
(define player-hitbox (make-frect 100.5 200.0 32.0 32.0))
13.2 Rectangle Accessors
procedure
(rect-x r) → exact-integer?
r : SDL_Rect?
procedure
(rect-y r) → exact-integer?
r : SDL_Rect?
procedure
(rect-w r) → exact-integer?
r : SDL_Rect?
procedure
(rect-h r) → exact-integer?
r : SDL_Rect?
procedure
(rect->values r) →
exact-integer? exact-integer? exact-integer? exact-integer? r : SDL_Rect?
(define-values (x y w h) (rect->values player-hitbox))
procedure
(frect->values r) →
real? real? real? real? r : SDL_FRect?
13.3 Collision Detection
procedure
(rects-intersect? a b) → boolean?
a : SDL_Rect? b : SDL_Rect?
(when (rects-intersect? player-hitbox enemy-hitbox) (handle-collision!))
procedure
(rect-intersection a b) → (or/c SDL_Rect? #f)
a : SDL_Rect? b : SDL_Rect?
(define overlap (rect-intersection a b)) (when overlap (printf "Overlap area: ~a x ~a~n" (rect-w overlap) (rect-h overlap)))
procedure
(frects-intersect? a b) → boolean?
a : SDL_FRect? b : SDL_FRect?
procedure
(frect-intersection a b) → (or/c SDL_FRect? #f)
a : SDL_FRect? b : SDL_FRect?
13.4 Rectangle Utilities
procedure
(rect-union a b) → SDL_Rect?
a : SDL_Rect? b : SDL_Rect?
(define bounds (rect-union a b))
procedure
(frect-union a b) → SDL_FRect?
a : SDL_FRect? b : SDL_FRect?
procedure
(rect-enclosing-points points [clip]) → (or/c SDL_Rect? #f)
points : (listof point?) clip : (or/c SDL_Rect? #f) = #f
SDL_Point structs
Lists of two numbers: (list x y)
Vectors of two numbers: #(x y)
If clip is provided, points are first clipped to that rectangle. Returns #f if no points are enclosed (or the list is empty).
(define bounds (rect-enclosing-points (list '(10 20) '(50 60) '(30 40))))
procedure
(frect-enclosing-points points [clip]) → (or/c SDL_FRect? #f)
points : (listof point?) clip : (or/c SDL_FRect? #f) = #f
13.5 Line Intersection
procedure
(rect-line-intersection rect x1 y1 x2 y2)
→
(or/c (values exact-integer? exact-integer? exact-integer? exact-integer?) #f) rect : SDL_Rect? x1 : real? y1 : real? x2 : real? y2 : real?
Returns (values x1-clipped y1-clipped x2-clipped y2-clipped) with the clipped line endpoints, or #f if the line doesn’t intersect the rectangle.
(define-values (cx1 cy1 cx2 cy2) (or (rect-line-intersection viewport 0 0 800 600) (values 0 0 0 0)))
procedure
(frect-line-intersection rect x1 y1 x2 y2)
→ (or/c (values real? real? real? real?) #f) rect : SDL_FRect? x1 : real? y1 : real? x2 : real? y2 : real?
Returns (values x1-clipped y1-clipped x2-clipped y2-clipped) with the clipped line endpoints, or #f if the line doesn’t intersect the rectangle.