line Intersects Circle - Java java.lang

Java examples for java.lang:Math Geometry Line

Description

line Intersects Circle

Demo Code


//package com.java2s;

public class Main {
    public static boolean lineIntersectsCircle(int x1, int y1, int x2,
            int y2, int cx, int cy, int r) {
        // Adapted from http://www.vb-helper.com/howto_net_line_circle_intersections.html

        int dx = x2 - x1;
        int dy = y2 - y1;

        int A = dx * dx + dy * dy;
        int B = 2 * (dx * (x1 - cx) + dy * (y1 - cy));
        int C = (x1 - cx) * (x1 - cx) + (y1 - cy) * (y1 - cy) - r * r;
        int det = B * B - 4 * A * C;

        if (A <= 1 || det < 0) {
            return false;
        }//from  ww w . ja  va 2s .c  o m
        return true;
    }
}

Related Tutorials