Search code examples
3dgeometrypointprojectionplane

How to get distance from point to plane in 3d?


I have a triangle with points A, B, C and Point in space (P). How can I get distance from point to plane? I need to calc distance from P to plane, even when my triangle lie far away(or not above to the point, like on picture).

Point and triangle:


Solution

  • I assume you want to compute perpendicular distance between point and plane given 3 points on it forming a triangle. Here vector math approach:

    1. definitions

      let the triangle points be p0,p1,p2 and tested point p.

    2. plane normal

      first we need to obtain plane normal, that is simple vector multiplication of any two non parallel and non zero vectors inside the plane:

      n = cross( p1-p0 , p2-p0 )
      

      and normalize it to unit vector (to simplify stuff):

      n = n/|n|
      
    3. perpendicular distance

      we can exploit dot product for this so just crate a vector going from any point on the plane into your tested point and dot with unit normal ...

      dist = |dot ( p-p0 , n )|
      

      perp. dist

      the last absolute value (on scalar distance) will just get rid of the sign of the result which tells you if the point p is in direction of normal n or in opposite one sometimes such info is wanted so in such case remove the outermost abs value and use polygon winding and cross product operands order to maintain wanted normal direction.

    Here (look for [edit2]) you will find the cross , dot and || equations used if needed:

    so if I put all together in code like form:

    U.x=p1.x-p0.x; V.x=p2.x-p0.x; // basis vectors on the plane
    U.y=p1.y-p0.y; V.y=p2.y-p0.y;
    U.z=p1.z-p0.z; V.z=p2.z-p0.z;
    n.x=(U.y*V.z)-(U.z*V.y);      // plane normal
    n.y=(U.z*V.x)-(U.x*V.z);
    n.z=(U.x*V.y)-(U.y*V.x);
    dist = sqrt( (n.x*n.x) + (n.y*n.y) + (n.z*n.z) ); // normalized
    n.x /= dist;
    n.y /= dist;
    n.z /= dist;
    dist = abs( (p.x-p0.x)*n.x + (p.y-p0.y)*n.y + (p.z-p0.z)*n.z ); // your perpendicular distance