Aug
05
2008
Line to Circle Intersection data
Posted by: Keith H in ActionScript 3, Flash 9, tags: Circle, Intersection, LineHere is an ActionScript 3 function that will return intersection information between a segment and circle.
It's useful to me to know if a segment is partially intersecting with a circle or going completely through.
/*--------------------------------------------------------------------------- Returns an Object with the following properties: enter -Intersection Point entering the circle. exit -Intersection Point exiting the circle. inside -Boolean indicating if the points of the line are inside the circle. tangent -Boolean indicating if line intersect at one point of the circle. intersects -Boolean indicating if there is an intersection of the points and the circle. If both "enter" and "exit" are null, or "intersects" == false, it indicates there is no intersection. This is a customization of the intersectCircleLine Javascript function found here: http://www.kevlindev.com/gui/index.htm ----------------------------------------------------------------------------*/ function lineIntersectCircle(A : Point, B : Point, C : Point, r : Number = 1):Object { var result : Object = new Object (); result.inside = false; result.tangent = false; result.intersects = false; result.enter=null; result.exit=null; var a : Number = (B.x - A.x) * (B.x - A.x) + (B.y - A.y) * (B.y - A.y); var b : Number = 2 * ((B.x - A.x) * (A.x - C.x) +(B.y - A.y) * (A.y - C.y)); var cc : Number = C.x * C.x + C.y * C.y + A.x * A.x + A.y * A.y - 2 * (C.x * A.x + C.y * A.y) - r * r; var deter : Number = b * b - 4 * a * cc; if (deter <= 0 ) { result.inside = false; } else { var e : Number = Math.sqrt (deter); var u1 : Number = ( - b + e ) / (2 * a ); var u2 : Number = ( - b - e ) / (2 * a ); if ((u1 < 0 || u1 > 1) && (u2 < 0 || u2 > 1)) { if ((u1 < 0 && u2 < 0) || (u1 > 1 && u2 > 1)) { result.inside = false; } else { result.inside = true; } } else { if (0 <= u2 && u2 <= 1) { result.enter=Point.interpolate (A, B, 1 - u2); } if (0 <= u1 && u1 <= 1) { result.exit=Point.interpolate (A, B, 1 - u1); } result.intersects = true; if (result.exit != null && result.enter != null && result.exit.equals (result.enter)) { result.tangent = true; } } } return result; }
Entries (RSS)
[...] « Line to Circle Intersection data Aug 08 2008 [...]
Very impressive. What about the intersection points of a line with a Bézier curve using the curveTo() function?
Very useful. I saved my time. Many thanks.
Great – exactly what I needed, and it works perfectly. Thanks
You helped me in the struggle with lethal deadlines : thanx !
[...] anyone had written a class to handle this. Keith Hair wrote a very nice class that does this with a circle. Aaron Clinger and Mike Creighton wrote a a very nice Ellipse class, but it doesn’t deal with [...]
good find and adaptation.