Tallan's Technology Blog

Tallan's Top Technologists Share Their Thoughts on Today's Technology Challenges

Objective C – Testing if Line Segment intersets Circle

Jordan Piscitelli

Objective C implementation of this blog post that tells you if two points that form a line segment intersect a circle at a point with a radius.

+ (BOOL) doesLineFromPoint: (CGPoint) A toPoint: (CGPoint) B intersectCircleAtPoint: (CGPoint) C withRadius:(CGFloat) r {

    BOOL inside = false;
    //BOOL tangent = false;
    BOOL intersects = false;
    //CGPoint enter;
    //CGPoint exit;

    CGFloat a = (B.x - A.x) * (B.x - A.x) + (B.y - A.y) * (B.y - A.y);
    CGFloat b = 2 * ((B.x - A.x) * (A.x - C.x) +(B.y - A.y) * (A.y - C.y));
    CGFloat cc = 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;
    CGFloat deter = b * b - 4 * a * cc;

    if (deter <= 0 ) {
        inside = false;
    } else {
        CGFloat e  = sqrt(deter);
        CGFloat u1 = ( - b + e ) / (2 * a );
        CGFloat u2 = ( - b - e ) / (2 * a );
        if ((u1 < 0 || u1 > 1) && (u2 < 0 || u2 > 1)) {
            if ((u1 < 0 && u2 < 0) || (u1 > 1 && u2 > 1)) {
                inside = false;
            } else {
                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);
            }
            intersects = true;
            //if (result.exit != null && result.enter != null && result.exit.equals (result.enter)) {
            //    result.tangent = true;
            //}
        }
    }
    return inside || intersects;
}

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

\\\