Hallo,
hab ein kleines Programm gebastelt, in dem der Schnittpunkt zwischen einer Geraden und einem Kreis dargestellt werden soll.
Gerade: bestimmt durch Kreismittelpunkt und Mauszeiger
Problem: die Determinante bei der Schnittpunktberechnung kann < 0 werden, obwohl die Gerade den Kreis immer schneidet!
außerdem sind die berechneten Schnittpunkte fast nie identisch mit der eigentlichen Geraden und dem Kreis. ? Rundungsfehler ?
hab ein kleines Programm gebastelt, in dem der Schnittpunkt zwischen einer Geraden und einem Kreis dargestellt werden soll.
Gerade: bestimmt durch Kreismittelpunkt und Mauszeiger
Problem: die Determinante bei der Schnittpunktberechnung kann < 0 werden, obwohl die Gerade den Kreis immer schneidet!
Code:
public void mouseMoved(MouseEvent me) {
int mousePosX = me.getX();
int mousePosY = me.getY();
this.intersection.setMousePos(mousePosX, mousePosY);
int intersectionY = 0;
int intersectionX = 0;
if(mousePosY >= Settings.kreismittelpunktY){
intersectionY = Settings.kreismittelpunktY;
if(mousePosX < Settings.kreismittelpunktX){
intersectionX = Settings.kreismittelpunktX - Settings.radius;
}else{
intersectionX = Settings.kreismittelpunktX + Settings.radius;
}
}else if(mousePosX - Settings.kreismittelpunktX == 0){
intersectionX = Settings.kreismittelpunktX;
intersectionY = Settings.kreismittelpunktY - Settings.radius;
} else {
// eigentliche Schnittpunktberechnung
// Gerade: y = g_m * x + g_b Kreis: (x - xm)^2 + (y - ym)^2 = r^2
double g_m = (mousePosY - Settings.kreismittelpunktY)
/ (mousePosX - Settings.kreismittelpunktX);
double g_b = mousePosY - (g_m * mousePosX);
double a = 1 + Math.pow(g_m, 2.0);
double b = (2.0 * g_m * g_b)
- (2.0 * g_m * Settings.kreismittelpunktY)
- (2.0 * Settings.kreismittelpunktX);
double c = Math.pow(g_b, 2.0)
- (2.0 * g_b * Settings.kreismittelpunktY)
+ Math.pow(Settings.kreismittelpunktY, 2.0)
- Math.pow(Settings.radius, 2.0)
+ Math.pow(Settings.kreismittelpunktX, 2.0);
System.out.println(" Determinante:"+Math.sqrt(Math.pow(b, 2.0)- (4 * a * c)));
// Schnittpunkt: nur den SP in der oberen Kreishälfte anzeigen
if (mousePosX < Settings.kreismittelpunktX) {
intersectionX = (int) Math.min(((b * (-1) - Math.sqrt(Math.pow(
b, 2.0)
- (4 * a * c))) / (2 * a)), ((b * (-1) + Math.sqrt(Math
.pow(b, 2.0)
- (4 * a * c))) / (2 * a)));
} else if (mousePosX > Settings.kreismittelpunktX) {
intersectionX = (int) Math.max(((b * (-1) - Math.sqrt(Math.pow(
b, 2.0)
- (4 * a * c))) / (2 * a)), ((b * (-1) + Math.sqrt(Math
.pow(b, 2.0)
- (4 * a * c))) / (2 * a)));
}
// r^2 - (x - kreismittelpunktX)^2
double circlePart = Math.pow(Settings.radius, 2.0)
- Math.pow((kreismittelpunktX - Settings.kreismittelpunktX), 2.0);
intersectionY = (int) Math.min((Settings.kreismittelpunktY + Math
.sqrt(circlePart)), (Settings.kreismittelpunktY - Math
.sqrt(circlePart)));
}
System.out.println(" x:"+intersectionX+" y:"+intersectionY);
this.intersection.setIntersectionPos(intersectionX, intersectionY);
}
Zuletzt bearbeitet: