John Fraser Computer Contest Club

Forums

Post Reply
Forum Home > Turing > Collision Test - Rectangle to Rectangle

Rui Lin
Moderator
Posts: 8

How to Check Collision Between Two Rectangles


Theory


If you haven't already, take a look at the collision between a rectangle and a point. This algorithm builds on that knowledge.


We'll define the following variables for the two rectangles. 

Note that the restriction x1 <= x2, and y1 <= y2 still applies.


We'll use an elimination process to determine if the two collide:

  • if the left side of A is greater than the right side of B, collision is not possible
  • if the left side of B is greater than the right side of A, collision is not possible
  • if the bottom side of A is greater than the top side of B, collision is not possible
  • if the bottom side of B is greater than the top side of A, collision is not possible
Put into code, this becomes:

if ax1 > bx2 or bx1 > ax2 or % x coordinate

   ay1 > by2 or by1 > ay2 then % y coordinate

% no collision

else

% collision

end if


 

Sample Program


% Rectangle Collision Demo

% Author: Rui Lin


% Checks if a rectangle intersects another rectangle

function rectIntersectsRect (x1 : int, y1 : int, x2 : int, y2 : int, x3 : int, y3 : int, x4 : int, y4 : int) : boolean


% Makes sure x1 <= x2, and y1 <= y2 for both rectangles

var ax1, ay1, ax2, ay2, bx1, by1, bx2, by2 : int

ax1 := min (x1, x2)

ay1 := min (y1, y2)

ax2 := max (x1, x2)

ay2 := max (y1, y2)

bx1 := min (x3, x4)

by1 := min (y3, y4)

bx2 := max (x3, x4)

by2 := max (y3, y4)


if ax1 > bx2 or bx1 > ax2 or % x coordinate

   ay1 > by2 or by1 > ay2 then % y coordinate

result false

end if


result true

end rectIntersectsRect


proc display

var info : array 1 .. 8 of int

for i : 1 .. 8

info (i) := Rand.Int (0, 600)

end for

drawbox (info (1), info (2), info (3), info (4), red)

drawbox (info (5), info (6), info (7), info (8), blue)


if rectIntersectsRect (info (1), info (2), info (3), info (4), info (5), info (6), info (7), info(8)) then

put "COLLISION DETECTED!"

else

put "NO COLLISION DETECTED"

end if

end display


loop

cls

display

delay (1000)

end loop



It becomes quite evident now how useful a function is. Instead of having to type all that code in every time you want to check rectangle collision, all you have to do is call the function with the coordinates of the rectangles, and it'll tell you if they collide. Saves a lot of time, believe me :D

October 10, 2010 at 6:36 PM Flag Quote & Reply

You must login to post.