# How to get the nearest polygon face and height of intersection point

I have multiple 3D polygons meshes (sketchup format) in the world, for any specified point (x,y,z), how do I get the direct closest polygon face below this point? and how to get the height for the projected intersection point on the face?

Can someone point me the direction how to get started?

To get the height intersection once you have found the polygon, you can build a plane of the polygon and calculate the distance to the plane. For example you can displace the point along the planes normal and calculate the length of the normal for when the point is displaced into the plane. Implicit planes are neat for this, they are build with the normal of the plane (which is the normal of the polygon) and one constant $d$. $d$ can be calculated by arbitrary point on the plane (e.g. one of your polygon vertices).

$d = -\vec{n} \cdot q$ and $\vec{n} + d = 0$ (where $\vec{n}$ is the normal and $q$ the point/vertex).

The neat part is: if you calculate the dot product of your point you want the distance of, you have the signed distance toward the plane, i.e. if $p$ is your point and $l$ is the distance between the point and the plane, then

$l = (\vec{n} + d) \cdot p$ (for this you assume the fourth coordinate of a point as $1$)

Now that you have the distance to the plane, you need to check, weather the intersection of normal through point with plane also intersects the polygon. You could for example take the vectors $\vec{v}_i = v_i - p$ where $v_i$ are your polygons, and then take the dot product $\vec{n} \cdot \vec{v}$. If they all have the same sign, your intersection doesn't hit the polygon (assuming the polygon to be convex).

Iff it doesn't hit the vertices you need the distance to the closest two vertices. Since you have already done the dot product test (with the sign) for all polygon vertices, you know that the shortest distance can't be to the edge between the two vertices, and thus it suffices to take the shortest of the two point->vertex distances.

As to which polygon is closest, I'm not sure if there is a better trick, but I'd just transform the point into Model Space of the mesh and calculate the distance to any front facing face.