I am trying to find the point of intersection of a circle and a line through its center. I want to put an arrow on the point actually, to make a directed graph. After some calculations, I found that the math that would go in is,
The figure of reference is:
The code I am using to achieve this is:
private Point getArrow(Point center, Point line) {
Point interesection;
int a = line.x;
int b = center.x;
int c = line.y;
int d = center.y;
int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
if ((b - a) != 0) {
try {
x1 = (int) (b + ((20 * (a - b)) / Math.sqrt((Math.pow((a - b), 2)) + Math.pow(c - d, 2))));
x2 = (int) (b - ((20 * (a - b)) / Math.sqrt((Math.pow((a - b), 2)) + Math.pow(c - d, 2))));
y1 = (int) (((d - c) / (b - a)) * (x1 - a) + c);
y2 = (int) (((d - c) / (b - a)) * (x2 - a) + c);
} catch (ArithmeticException ex) {
if ((a - b) == 0) {
y1 = y2 = 0;
} else if ((a - b) == 0 && (c - d) == 0) {
x1 = x2 = y1 = y2 = 0;
}
}
} else {
return new Point(center.x+19, center.y - 5);
}
Point p1 = new Point(x1+19, y1+19);
Point p2 = new Point(x2+19, y2+19);
if (line.distanceSq(p2) < line.distanceSq(p1)) {
interesection = new Point(p2);
} else {
interesection = new Point(p1);
}
return interesection;
}
Can anyone tell me why my code is breaking for the math? I am trying to plot the point returned as a filled oval of width and height being 5. The radius of the original circle is 20.