所以我是一个很新的人,而且我一直在玩一些东西,但有一点我无法弄清楚如何计算一个点到一条线的距离。我可以用铅笔和纸自己轻松地做到这一点,但是当我真正尝试将它应用于shadertoy时,不知何故我一直搞砸了。这就是我所拥有的:
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord/iResolution.xy;
uv.x -= 0.5; //Puts the origin at the center of the screen
float r; //Red value
float g; //Green value
float b; //Blue value
float lm = 1.1; //slope
float lb = 0.5; //intercept
//Slope/intercept declarations manipulate line
//second line
float lmp = 0.0-(1.0/lm); //calculates the slope of the perpendicular line
float lbp = lb + uv.y + lmp*(uv.x); //and the intercept
//Intersection
float ix = (lbp-lb)/(lm-lmp); //Intersection Y
float iy = lm*(ix)+lb; //Intersection X based off of the first equation
//distance
float dist = sqrt(pow((uv.x - ix),2.0)+pow((uv.y - iy),2.0));
if (dist < 0.05){
r = 1.0;
g = 1.0;
b = 1.0;
}
fragColor = vec4(r,g,b,1.0); //supposed to draw a line
}
现在来自Flyguy的“Neontoy”项目不仅有效,而且比我的短得多。
float dfLine(vec2 start, vec2 end, vec2 uv)
{
start *= scale;
end *= scale;
vec2 line = end - start;
float frac = dot(uv - start,line) / dot(line,line);
return distance(start + line * clamp(frac, 0.0, 1.0), uv);
}
如果你有一条线,由一个点(O
)和一个方向(D
)给出,那么线上最近的点到点p可以按如下方式计算
X = O + D * dot(P-O, D);
2个矢量的点积等于2个矢量之间的角度的余弦乘以两个矢量的幅度(长度)。
dot( A, B ) == | A | * | B | * cos( alpha )
V
和D
的点积等于线(O
,D
)和矢量V = P - O
之间的角度的余弦,乘以V
的量(长度),因为D
是unit vector(D
的长度是1.0) ,
在你的情况下,该行由Linear equation以下列形式给出:
f(x) = lb + lmp * x;
线上的点是(0.0,lb
),方向是(1.0,lmp
)。
将其应用于您的代码会产生以下片段着色器:
float dfLine(vec2 O, vec2 dir, vec2 P)
{
vec2 D = normalize(dir);
vec2 X = O + D * dot(P-O, D);
return distance(P, X);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord/iResolution.xy;
uv.x -= 0.5; //Puts the origin at the center of the screen
float lm = 1.1; //slope
float lb = 0.5; //intercept
float dist = dfLine(vec2(0.0, lb), vec2(1.0, lmp));
float onLine = step(dist, 0.05); // 1.0 if on line, else 0.0
vec3 color = onLine * vec3(1.0);
fragColor = vec4(color, 1.0);
}