John Fraser Computer Contest Club

Forums

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

Rui Lin
Moderator
Posts: 8

How to Check If Two Circles Are Intersecting


Theory

Lets say there are two circles, A, and B. We'll use the following variables

Ax, Ay, Ar, and Bx, By, Br


[where (Ax, Ay) and (Bx, By) defines the centres of the circles, and Ar, Br, are their radius respectively.]




As you can see here, whenever two circle are colliding, touching, intersecting, whatever you want to call it, the distance between their centers, is always equal to, or less than the two radii combined.


We can put this information into code:


% checks if two circles are colliding

if Math.Distance (Ax, Ay, Bx, By) <= Ar + Br then

% do something, the circles collided

else

% the circles are not touching

end if


Note that turing has a very convenient function that calculates the distance between two points for you. Otherwise you could always do it yourself with Pythagorean theorem.


sqrt ( (Ax-Bx) * (Ax-Bx) + (Ay-By) * (Ay-By) ) <= Ar + Br


You can actually optimize this code, by squaring both sides of the equation. This gets rid of the nasty sqrt function, which is very slow compared to multiplication. This gives you:


(Ax-Bx) * (Ax-Bx) + (Ay-By) * (Ay-By) <= (Ar+Br) * (Ar+Br)


For convenience, you can also make this into a function for easy reuse. If you haven't used functions before, it'd be in your best interest to do so, as it will help greatly in making larger programs.


% Checks if a circle intersects a circle

function circleIntersectsCircle (Ax : int, Ay : int, Ar : int, Bx : int, By : int, Br : int) : boolean

result Math.Distance (Ax, Ay, Bx, By) <= Ar + Br

end circleIntersectsCircle



Sample Program


% Circle Collision Demo

% Author: Rui Lin

%

 

% Checks if a circle intersects a circle

function circleIntersectsCircle (Ax : int, Ay : int, Ar : int, Bx : int, By : int, Br : int) : boolean

result Math.Distance (Ax, Ay, Bx, By) <= Ar + Br

end circleIntersectsCircle

 

proc display

var info : array 1 .. 6 of int

for i : 1 .. 6

put "Enter a number: " ..

get info (i)

end for

drawoval (info(1), info(2), info(3), info(3), red)

drawoval (info(4), info(5), info(6), info(6), blue)

 

if circleIntersectsCircle(info(1),info(2),info(3),info(4),info(5),info(6)) then

put "COLLISION DETECTED!"

else

put "NO COLLISION DETECTED"

end if

end display

 

loop

cls

display

delay (3000)

end loop

 


The advantage of using a function is to faciliate code reuse, so you don't have to retype the logic over and over again every time you want to check collision, reducing accidental errors. The saved time may not be as apparent in such a simple collision check, but it will be more obvious in more difficult ones, such as circle to rectangle, for example.


October 10, 2010 at 5:09 PM Flag Quote & Reply

You must login to post.