|
x1 - x coordinate of the first rectangle's top left corner y1 - y coordinate of the first rectangle's top left corner width1 - width of the first rectangle height1 - height of the first rectangle x2 - x coordinate of the second rectangle's top left corner y2 - y coordinate of the second rectangle's top left corner width2 - width of the second rectangle height2 - height of the second rectangle |
|
Returns True if two rectangles overlap. No images are involved, which makes this the fastest collision test in the language - four comparisons and done. Rectangles that merely share an edge do not count as overlapping; there has to be real area in common. Because it takes plain numbers it fits anywhere you keep your own bounds: Types with x, y, w and h fields, a tile grid, a camera frustum in 2D, a mouse pointer against a menu entry, or a broad-phase pass that throws out the obvious misses before you call the expensive ImagesCollide on what is left. It is also how you build collision boxes that do not match the artwork - a tighter hitbox than the sprite, a generous pickup radius, or a hurtbox offset from a character's feet. Sprite-based tests cannot do that; this one can, because you decide what the rectangles are. The parameters are a corner plus a size, not two corners. Mixing that up is the usual reason a test seems to fire at the wrong moment. See also: ImagesOverlap, ImagesCollide, ImageRectOverlap, ImageRectCollide. |
; RectsOverlap Example
; --------------------
Graphics 640,480,0,2
SetBuffer BackBuffer()
; The player rectangle, steered with the arrow keys
px=100
py=100
While Not KeyDown(1)
Cls
If KeyDown(203) Then px=px-3
If KeyDown(205) Then px=px+3
If KeyDown(200) Then py=py-3
If KeyDown(208) Then py=py+3
; Pure rectangle maths - no images involved, the fastest overlap test
hit=RectsOverlap(px,py,60,40,270,190,100,100)
; The fixed zone - red while the player rectangle overlaps it
If hit Then
Color 255,60,60
Else
Color 80,200,80
End If
Rect 270,190,100,100,False
; The player rectangle
Color 255,255,255
Rect px,py,60,40,True
Text 0,0,"Arrow keys: move your rectangle into the zone Esc: exit"
Text 0,20,"RectsOverlap("+px+","+py+",60,40,270,190,100,100)="+hit
Flip
Wend
End