如何在GLSL中实现从点到线段的距离? [英] How can I implement the distance from a point to a line segment in GLSL?

查看:378
本文介绍了如何在GLSL中实现从点到线段的距离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法在这里发现我的错误,可以吗?

I just can't seem to spot my bug here, can you?

bool oblong (vec2 p, vec2 a, vec2 b, float r) {
 return (((b.y-a.y)*(p.x-a.x)+(b.x-a.x)*(p.y-a.y))^2/((b.x-a.x)^2+(b.y-a.y)^2)<= r);
}

这是我的第二个GLSL程序,(我的第一个是一个圆圈.)谢谢您的输入!

This is my second GLSL program, (my first was a circle.) Thanks for your input!

推荐答案

您不能很好地解释该函数应该执行的操作以及单字符变量名称的实际含义.我猜想ab是线段上的点,而p是感兴趣的点. r必须是该功能要测试的距离(通常,您应该返回该距离并让用户对其进行测试.如果要保留该距离,则该位置是特权).

You don't explain very well what the function is supposed to do and what your single-character variable names actually mean. I'm going to guess that a and b are the points on the line segment, and p is the point of interest. r must be some distance that the function tests against (generally, you should return the distance and let the user test against it. If they want to keep it, it's there prerogative).

我猜你真正的问题是在C,C ++或GLSL中,^都不是提高能力"运算符.

I guess your real problem is that in neither C, C++, or GLSL is ^ the "raise to a power" operator.

在任何情况下,此功能的正确版本如下:

In any case, a correct version of this function would be as follows:

float DistToLine(vec2 pt1, vec2 pt2, vec2 testPt)
{
  vec2 lineDir = pt2 - pt1;
  vec2 perpDir = vec2(lineDir.y, -lineDir.x);
  vec2 dirToPt1 = pt1 - testPt;
  return abs(dot(normalize(perpDir), dirToPt1));
}

请注意,此代码尚未经过测试.我只是在执行给定站点上提供的解决方案.这是使用矢量算术以矢量符号实现的.请注意,我很少获得X和Y分量(我只做过一次以获得垂直分量).

Note that this code has not been tested. I'm just implementing the solution presented at the given site. This is implemented in vector notation with vector arithmetic. Note that I very rarely get the X and Y components (I only do it once to get the perpendicular).

这篇关于如何在GLSL中实现从点到线段的距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆