how to check if a line segment intersects a circle
Afficher commentaires plus anciens
is there any formula to check whether a line intersects a circle in matlab.can someone help me out. suppose i have got a line segemtn with ends x,y and x1,y2 and there is a circle with centre h,k with radius r. how can i know if the line segement intersects the circle or not
2 commentaires
Borison ningthoujam
le 21 Mai 2018
Réponse acceptée
Plus de réponses (1)
Truong Nhu
le 12 Avr 2022
Modifié(e) : Truong Nhu
le 12 Avr 2022
I have a more rounded solution for anybody who need it. For your information, I found this on Stackoverflow. If you want to understand the math behind it follow this link Behind-the-scene Math.
P1, P2 is the two points of the line segment. C is then center of the circle.
function flag_intersect = intersect_line_cir(P1,P2,C,radius)
d = P2 - P1;
f = P1 - C;
r = radius;
a = dot(d,d);
b = 2*dot(f,d);
c = dot(f,f) - r^2;
discriminant = b*b-4*a*c;
if( discriminant < 0 )
% // no intersection
flag_intersect = false;
return
else
% // ray didn't totally miss sphere,
% // so there is a solution to
% // the equation.
discriminant = sqrt( discriminant );
% // either solution may be on or off the ray so need to test both
% // t1 is always the smaller value, because BOTH discriminant and
% // a are nonnegative.
t1 = (-b - discriminant)/(2*a);
t2 = (-b + discriminant)/(2*a);
% // 3x HIT cases:
% // -o-> --|--> | | --|->
% // Impale(t1 hit,t2 hit), Poke(t1 hit,t2>1), ExitWound(t1<0, t2 hit),
% // 3x MISS cases:
% // -> o o -> | -> |
% // FallShort (t1>1,t2>1), Past (t1<0,t2<0), CompletelyInside(t1<0, t2>1)
if( t1 >= 0 && t1 <= 1 )
% // t1 is the intersection, and it's closer than t2
% // (since t1 uses -b - discriminant)
% // Impale, Poke
flag_intersect = true;
return
end
% // here t1 didn't intersect so we are either started
% // inside the sphere or completely past it
if( t2 >= 0 && t2 <= 1 )
% // ExitWound
flag_intersect = true;
return
end
% // no intn: FallShort, Past, CompletelyInside
flag_intersect = false;
return
end
Catégories
En savoir plus sur Descriptive Statistics dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!