I need an algorithm (3D), which would determine if point belongs to a triangle. And also if it does I want to know the distance between some point in triangle and a another point. Triangles can be slightly rotated, but if point is outside triangles vertical reach then it should not be considered as inside the triangle.
Now I realize, my question probably doesn't make a lot of sense so here's the picture, which explains what I want.
Grey lines display, which way triangle is actually facing.
It's not actually that I want to check if a point is within a prism, but I after i find out if point lies within triangle (not exactly, might be on top of or below) then I need to find the distance between point and a triangle it belongs to. And depending on the distance function will finally return if that point is inside the triangle. A little inaccuracy is allowed. However, maybe I want to check if a point is within a prism, but do not know that. I am just horrible at math so I am not aware of correct terminology.
This can be split into 2 problems.
(and use own logic to test if this distance is considered close or not).
Withe the example below, you can do a check, for eg:
... where
eps
is the distance to consider points 'on the triangle'.This code example uses functional Python so should be easy to move to other languages, it uses only simple arithmetic, no
sqrt
or complex functions.This seems like the 3D equivalent of Data structure to query points which lie inside a triangle. You could use the same method in 3D: in 3D, a plane cuts the space in two halves: a point is either at one side of the plane or at the other side. The wedge-shape is a collection of planes: just combine the which_side_of_the_plane information for a given point with all the planes that build up the wedge.
You can use a cylindrical version of barycentric coordinates. I've only checked this for prisms that rise perpendicular from the triangular base -- another way to put this is that we are orthogonally projecting the point into the plane defined by the triangle, and checking if it is inside or not.
If you want more details on the math ask (or better yet, try to figure it out yourself since it's a neat little exercise).
If our triangle is
ABC
(non-degenerate), thenN = (B-A)x(C-A)
(cross product) is a normal to the (unique) plane defined by the triangle. Call the point we want to testP
.Now calculate the value
a' = N . ((P-B) x (P-C))
(where.
is dot product).a'
is the usual barycentric coordinate multiplied byN.N
(which is positive).Similarly, we find
b' = N . ((P-C) x (P-A))
andc' = N . ((P-A) x (P-B))
. If all three of 'a'', 'b'', and 'c'' are non-negative, then the projection of P is inside the triangle (if you want to exclude the triangle itself, then all three must be strictly positive).