circle line intersection java

Solutions on MaxInterview for circle line intersection java by the best coders in the world

showing results for - "circle line intersection java"
Harley
07 Jul 2017
1import java.util.Arrays;
2import java.util.Collections;
3import java.util.List;
4
5public class CircleLine {
6
7    public static List<Point> getCircleLineIntersectionPoint(Point pointA,
8            Point pointB, Point center, double radius) {
9        double baX = pointB.x - pointA.x;
10        double baY = pointB.y - pointA.y;
11        double caX = center.x - pointA.x;
12        double caY = center.y - pointA.y;
13
14        double a = baX * baX + baY * baY;
15        double bBy2 = baX * caX + baY * caY;
16        double c = caX * caX + caY * caY - radius * radius;
17
18        double pBy2 = bBy2 / a;
19        double q = c / a;
20
21        double disc = pBy2 * pBy2 - q;
22        if (disc < 0) {
23            return Collections.emptyList();
24        }
25        // if disc == 0 ... dealt with later
26        double tmpSqrt = Math.sqrt(disc);
27        double abScalingFactor1 = -pBy2 + tmpSqrt;
28        double abScalingFactor2 = -pBy2 - tmpSqrt;
29
30        Point p1 = new Point(pointA.x - baX * abScalingFactor1, pointA.y
31                - baY * abScalingFactor1);
32        if (disc == 0) { // abScalingFactor1 == abScalingFactor2
33            return Collections.singletonList(p1);
34        }
35        Point p2 = new Point(pointA.x - baX * abScalingFactor2, pointA.y
36                - baY * abScalingFactor2);
37        return Arrays.asList(p1, p2);
38    }
39
40    static class Point {
41        double x, y;
42
43        public Point(double x, double y) { this.x = x; this.y = y; }
44
45        @Override
46        public String toString() {
47            return "Point [x=" + x + ", y=" + y + "]";
48        }
49    }
50
51
52    public static void main(String[] args) {
53        System.out.println(getCircleLineIntersectionPoint(new Point(-3, -3),
54                new Point(-3, 3), new Point(0, 0), 5));
55        System.out.println(getCircleLineIntersectionPoint(new Point(0, -2),
56                new Point(1, -2), new Point(1, 1), 5));
57        System.out.println(getCircleLineIntersectionPoint(new Point(1, -1),
58                new Point(-1, 0), new Point(-1, 1), 5));
59        System.out.println(getCircleLineIntersectionPoint(new Point(-3, -3),
60                new Point(-2, -2), new Point(0, 0), Math.sqrt(2)));
61    }
62