0

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

4

1 回答 1

0

你的方程推导有错误,所以至少第二个和的符号是错误的 (也避免在向量计算中使用斜率)

 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

关于距离:我们需要找到从点P到直线的垂线长度。这个长度是斜边(P-P0)长度乘以角度的正弦,所以我们可以使用向量(P-P0)和方向单位向量的叉积normvec来得到距离。

快速检查:

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
于 2018-04-22T02:09:31.077 回答