Collisions are important in games. Java has a simple built in collision method that detects if two rectangles collide (ie. intersect). There is nothing for any other shape.
We want to write a program to determine if a line and a circle intersect.
You can download and run my program to see how it looks: CircleLineIntersect.jar. Windows: click on the jar file to run it. Linux (and Mac?) in a terminal type "java -jar CircleLineIntersect"
Please colour code the background so that it shows which situation the line and circle are in.
NOTE: to start with you can just hardcode the coordinates of the circle and line. Later on you can make them draggable.
DrawingPanel panel;
Circle circle;
Point l1, l2;
[...]
circle = new Circle(270,250,100);
l1 = new Point(150,150);
l2 = new Point(600,200);
[...]
class Circle {
int x,y,r;
Circle(int x, int y, int r) {
this.x = x;
this.y = y;
this.r = Math.abs(r); //negative radii not allowed
}
void paint(Graphics2D g2) {
g2.setColor(Color.BLACK);
g2.drawOval(x-r, y-r, r+r, r+r);
}
}