Hi all Is there an easy way to determine if a point inside a triangle? It's 2D not 3D.
Best Regards,
Hi all Is there an easy way to determine if a point inside a triangle? It's 2D not 3D.
Best Regards,
google search: http://mathforum.org/library/drmath/view/54505.html
Here's some high quality info in this topic on GameDev, including performance issues.
And here's some code to get you staret:
float sign(fPoint p1, fPoint p2, fPoint p3)
{
return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
}
bool PointInTriangle(fPoint pt, fPoint v1, fPoint v2, fPoint v3)
{
bool b1, b2, b3;
b1 = sign(pt, v1, v2) < 0.0f;
b2 = sign(pt, v2, v3) < 0.0f;
b3 = sign(pt, v3, v1) < 0.0f;
return ((b1 == b2) && (b2 == b3));
}
In general, the simplest (and quite optimal) algorithm is checking on which side of the half-plane created by the edges the point is.
A simple way is to:
find the vectors connecting the point to each of the triangle's three vertices and sum the angles between those vectors. If the sum of the angles is 2*pi then the point is inside the triangle.
Two good sites that explain alternatives are:
Solve the following equation system:
p = p0 + (p1 - p0) * s + (p2 - p0) * t
The point p
is inside the triangle if 0 <= s <= 1
and 0 <= t <= 1
and s + t <= 1
.
s
,t
and 1 - s - t
are called the barycentric coordinates of the point p
.
For my purposes (the reason I found this site) the original answer proposed by Kornel Kisielewicz is much more efficient. I'm working with an LCD display with BYTE size coordinates and a very typical microprocessor where integer multiply is a very fast instruction, and division is much, much, slower.
Numeric issues are also much smaller, due to no division! all calculations are exact.
Thanks,
Rick