| Forum Home > Turing > Collision Test - Circle to Line | ||
|---|---|---|
|
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:
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 | |
| ||