English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I need to know an easy way to calculate whether or not a point is in triangle ABC. This may sound easy but I haven't been able to figure it out yet. It's easy to do if you graph it but I need something where I could figure it out mathematically without looking at a graph or just imagining it. I need it for a program I'm making using C++ so if you know of a program that works using C++ that would be even better.

2007-01-24 11:15:15 · 2 answers · asked by antidisestablishmentarianism 2 in Science & Mathematics Engineering

if you suggest using the slope, what do you do when the slope is undefined...

2007-01-24 11:24:03 · update #1

2 answers

Just treat your triangle as being aligned on some coordinate system -- each edge of the triangle represents a line in the form y = mx + b where m is your slope and b is the intercept. In C++ you could use doubles to calculate the m values and then do comparisons on points that you want to determine the location with respect to the triangle. #include is your best friend.

Update:
With regards to your question about an undefined slope -- yes this is a special condition that you will need to check for in your program. However, when the slope is undefined you know that the line is either exactly vertical or horizontal so the problem is still trivial to solve.

2007-01-24 11:19:44 · answer #1 · answered by mdigitale 7 · 1 0

This requires a lot of if-then-else statements. Let's assume your triangle is given by three vertices A(x1,y1), B(x2, y2), and C(x3, y3). Then you must determine relative positions of A, B, C.
Without loosing generality you can place vertex A into origin so that A(0,0), and be left with B(x2-x1, y2-y1)=B(x2',y2') and C(x3-x1,y3-y1)=C(x3',y3'). Now you can place B on the x axis rotating your coordinate system by an angle theta=arctang(y2'/x2'). Your transformations come from old x'=r*cos(alpha), y'=r*sin(alpha) to new x"=r*cos(alpha-theta) and y"=r*sin(alpha-theta). Finally you will have triangle with A(0,0), B(x2",0) and C(x3",y3"). Having so defined triangle you can determine the sides: AB: x axis, AC: y=(y3"/x3")*x, and BC: y=(y3"/(x3"-x2"))(x-x2). Now you have two cases. If y3">0 then your arbitrary point (x0,y0) is outside of triangle iff: x0<0 or y0>(y3"/x3")*x0 or y0>(y3"/(x3"-x2"))(x0-x2). If y3"<0 then your arbitrary point (x0,y0) is outside the triangle iff: x0>0 or y0<(y3"/x3")*x0 or y0<(y3"/(x3"-x2"))(x0-x2).

2007-01-24 16:44:54 · answer #2 · answered by fernando_007 6 · 0 1

fedest.com, questions and answers