The program needs to read the values of three coordinates
- P1(x1,y1)
- P2(x2,y2)
- P3(x3,y3)
as well as another coordinate P(x,y) and determine whether this point is inside a triangle formed from the 3 point above.
The program needs to read the values of three coordinates
as well as another coordinate P(x,y) and determine whether this point is inside a triangle formed from the 3 point above.
Take the average of the three given points. This new point P4 will always lie inside the triangle.
Now check if P and P4 lie on the same side of each of the three lines
P1P2
P2P3
andP3P1
. You can do this by checking the signs of the cross products(P -> P1) x (P -> P2)
and(P4 -> P1) x (P4 -> P2)
(where P->P1 is the vector from P to P1), and then the other two pairs.Instead of P1, P2 and P3, lets assume the points as A,B and C.
Algorithm :
Given below is a program in C:
Time : O(1)
Space: O(1)
The proper way to do this is by calculating the barycentric coordinates of the fourth point given the three points of your triangle. The formula to compute them is given at the end of the section "Converting to barycentric coordinates", but I hope to provide a less mathematics-intense explanation here.
Assume, for simplicity, that you have a struct,
point
, that has valuesx
andy
. You defined your points as:Now, the barycentric coordinates, generally called
alpha
,beta
, andgamma
, are calculated as follows:If all of
alpha
,beta
, andgamma
are greater than0
, then the pointp
lies within the triangle made of pointsp1
,p2
, andp3
.The explanation behind this is that a point inside a triangle can be described using the points of the triangle, and three coefficients (one for each point, in the range [0,1]):
Rearranging this function gives you the formula to compute barycentric coordinates, but I feel like the steps to do so might be beyond the scope of the question. They are provided on the Wikipedia page that I linked up top.
It follows that each coefficient must be greater than 0 in order for the point
p
to lie within the area described by the three points.