Search code examples
mathvectordistancevectormath

Perpendicular Distance using Normal Vector


I'm currently writing a script that determines the shortest distance from a point to a line created by two vector points. This script is going to be used in a graphics program in order to do bezier clipping, so it'll be executed thousands of times.

Due to this requirement, I'm trying to utilize a normalized line between two points so that calculating distance won't be so taxing on the user. My problem, is that my algorithm doesn't seem to work despite my efforts to fix it.

CODE

for i=0,4 do
    p0:Set(math.random(-100,100),math.random(-100,100))
    p1:Set(math.random(-100,100),math.random(-100,100))
    v1:Set(math.random(-100,100),math.random(-100,100))

    local NormVec = p1-p0  --determine difference between 2 vectors
    NormVec:NormMe() --normalizes vector

    local slope = NormVec.y / NormVec.x 

    local YIntercept = p0.y-slope*p0.x

    local Dist = math.abs(NormVec.y*v1.x + NormVec.x*v1.y + 
    YIntercept)
end

In this code, I define some random vectors p0,p1,v1. I then determine a line between p0 and p1. I normalize the line. I then find the slope and use that to find the YIntercept. I finally plug this into the formula for distance for a normalized curve, but my results are always wrong.

Info on the Perpendicular Distance can be found on the following link: A mathematics website regarding relevant equations


Solution

  • Your equation derivation has mistakes, so at least sign of the second summand is wrong (also avoid using slopes in vector calculations)

     equation of line through two points:
    (x-x0) / (x1-x0) = (y-y0) / (y1-y0)
    (x1-x0) / dx = (y-y0) / dy
    normvec = (dx / length(dx,sy), dy / length(dx,sy))
    (x1-x0) / normvex.x = (y-y0) / normvec.y
    
    (x-x0) * normvec.y = (y-y0) * normvec.x
    so right equation is
    x * normvec.y - y * normvec.x + (y0 * normvec.x - x0 * normvec.y) = 0
    

    About distance: We need to find length of perpendicular from point P onto the line. This length is hypotenuse (P-P0) length multiplied by sine of angle, so we can uses cross-product of vector (P-P0) and direction unit vector normvec to get distance.

    Quick check:

    x0 = 4 y0 = 0 x1 = 0 y1 = 3
    normvec.x = 4/5 
    normvec.y =  - 3/5 
    equation
    x * -3/5  - y * 4/5 + 12/5 = 0
    DistanceTo(4,3)  = Abs(-12/5 - 12/5 + 12/5) = 12/5
    
    geometrical approach:
    height to archimedean triangle hypotenuse 
    Area = 1/2 * 3 * 4 = 1/2 * h * 5 so h = 12/5