John Fraser Computer Contest Club

Forums

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

Rui Lin
Moderator
Posts: 8

How to Check if a Circle is Touching a Line


Theory


At first glance this may seem quite difficult. However, we can break it down into two steps:

  • Finding the closest distance between a line and a point (the circle's center)
  • Checking if that distance is less than or equal to the circle's radius
We can do the first step mathematically, but it doesn't look very neat. Thankfully, Turing comes with a function that does it for us:

% where xp, yp are the coordinates of the point,
% and x1, y1, x2, y2 defines the line.
Math.DistancePointLine (xp, yp, x1, y1, x2, y2 : real) : real

Once we have the closest distance between the center of the circle, and the line, we can just check if that distance is within the circle's radius. If it is, they intersect, if not, they don't, eg:

if Math.DistancePointLine (cx, cy, x1, y1, x2, y2) <= cr then
% circle and line intersect
else
% circle and line don't intersect
end if

Sample Program

% Line vs Circle Collision Demo
% Author: Rui Lin

% Checks if a circle intersects a line

function circleIntersectsLine (cx : int, cy : int, cr : int, x1 : int, y1 : int, x2 : int, y2 : int) : boolean

result Math.DistancePointLine (cx, cy, x1, y1,x2,y2) <= cr

end circleIntersectsLine


proc display

var info : array 1 .. 7 of int

for i : 1 .. 7

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

end for

info (3) := Rand.Int (1, 400)

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

drawline (info(4), info(5), info(6), info(7), blue)

 

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

put "COLLISION DETECTED!"

else

put "NO COLLISION DETECTED"

end if

end display


loop

cls

display

delay (1000)

end loop

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

You must login to post.