# How to find the closest point on a plane

So I have this terrain with a perpendicular plane setup, now I want to move the vertices of the plane to their closest resp. vertices on the terrain. I made a drawing to illustrate my thoughts. Final result being the terrain will look like it has some thickness.

i also need the projection of the point on the terrain

I found this code on a previous thread :

    float distance = PointToPlaneDistance(smallObj.transform.position, wall.transform.position, wallNormal);

private float PointToPlaneDistance(Vector3 pointPosition, Vector3 planePosition, Vector3 planeNormal)
{
float sb, sn, sd;

sn = -Vector3.Dot(planeNormal, (pointPosition - planePosition));
sd = Vector3.Dot(planeNormal, planeNormal);
sb = sn / sd;

Vector3 result = pointPosition + sb * planeNormal;
return Vector3.Distance(pointPosition, result);
}


The result vector here is the closest point

But what is the plane normal? Unity has a built in mesh.normals which gives all the surface normals for the terrain. Which one should I use here?

Since your plane is perpendicular, you wouldn't use the normals. Just like your second drawing in your album:

Just ignore the Y and Z axis, of the terrain. For each point you want to match on the terrain, take the X axis value, and match that value on your perpendicular plane.

For example, if the point is at (1,3,0), just take the point (1,planeTop,0) on your plane.

Your terrain even appears to be a regular grid, meaning you can use a simple loop to iterate through the terrain vertices and match them with your plane vertices.

As for the projection, you don't have a flat plane, which is what that code is for. You have an uneven mesh. Using the normals will not help you. Just take the four values that make up the corners of the grid square you're directly above, then use linear interpolation to find the y value of the mesh at that point.

• That only changes the Z coordinate. So, in my example, in your loop, iterating over x: (x,planeTop,zDepth). It's still just one loop. Feb 22, 2015 at 21:03