Advertisement

Calculating if a point is within a triangle?

Started by October 03, 2002 01:04 PM
30 comments, last by DevLiquidKnight 22 years, 4 months ago
Im trying to come up with a way using C++ to determain if a point lies within a triangle. Does anyone know how to do this?
Here
"Literally, it means that Bob is everything you can think of, but not dead; i.e., Bob is a purple-spotted, yellow-striped bumblebee/dragon/pterodactyl hybrid with a voracious addiction to Twix candy bars, but not dead."- kSquared
Advertisement
sopose that you have the triangle (v1, v2, v3) and the point p

then if

(v2-v1)x(p-v1), (v3-v2)x(p-v2) and (v1-v3)x(p-v3) have all the same sign the point is in the triangle.

x is the vectorial product

// naher
MollerTrumbore97
http://www.acm.org/jgt/papers/MollerTrumbore97/
Basically, three half-plane tests that all have to return the same sign. This allows you to generate your normals in either direction, as long as they''re all consistant.
but how about p is in line v1 and v3??ie p, v1, v3 are collinear
Advertisement
Right, so to expand the half-plane test rule, all non-zero numbers have to be the same sign. If two of the numbers are zero though, then it''s automatically inside the triangle, because that means it''s colinear with two of the sides (i.e on the corner).
could u give a definition of each variable
Just a quick tip:

If you''re scanning through lots of triangles to see if the point falls within them, it can be handy to use a quick test to test if it DOESN''T lie in the triangle.
E.g. if x-value of the point is less than the x-values of the all the triangle corners, then you can skip that triangle.
Then you only use the proper point-in-triangle stuff if the quick tests pass.

I''m sure you get the idea. This should speed it up a little.
Each "variable" would be the distance from the point to each side respectively. The distance from the point to a side is defined by:

DotProduct(point, sideNormal) - DotProduct(sideNormal, known point on side)

But like tuita said, always perform the trivial tests first so you can possibly eliminate superfluous calculations.

This topic is closed to new replies.

Advertisement