射线与线段相交点

我在处理射线和线段相交时遇到问题。我使用Lua编码,但任何语言的示例都有用。

我大部分时间都在寻找算法或现有函数,以便我可以基于它们编写我的代码,前几天我发现了这个:

`` ` bool RayLineSegmentIntersection(const vec2&o,const vec2&d,const vec2&a,const vec2&b) { vec2正交(-d.y,d.x); vec2 aToO(o-a); vec2 aToB(b-a);

float denom = dot(aToB,ortho);

//也可以将这个叉积的长度写成aToB.x * aToO.y-aToO.x * aToB.y。 float t1 = length(cross(aToB,aToO))/ denom; float t2 = point(aToO,ortho)/ denom;

return t2> = 0 && t2 <= 1 && t1> = 0; } `` `

[来源](https://rootllama.wordpress.com/2014/05/26/point-in-polygon-test)

但是,我不确定作者所说的长度是什么,因为该评论只定义了叉积,没有定义函数长度。

我的实现类似,但由于我不知道他所说的长度是什么,因此我只是在那里进行叉积。问题在于,线段似乎被处理为射线,因为我正在获得不应该发生的交集,除非我正在相交的射线。例如,直接穿过矩形中心的射线正在报告它不应相交的其他矩形(我现在循环通过行)的交点。

有更好的方法实现吗,或者上面缺少的长度函数是修复此问题的方法吗?

这是我的预期和我认为正在发生的情况的粗略图:

[图纸](http://medpackstudios.com/images/expected.jpg)

点赞
用户1735680
用户1735680

几年前,我在我的简单绘图项目中使用了这个算法。我发现了这个算法并根据我的需求进行了调整。希望它能在某种程度上帮助到你。

            public virtual bool IsPointInPolygon(PointF[] polygon, PointF point)
            {
                bool isInside = false;
                for (int i = 0, j = polygon.Length - 1; i < polygon.Length; j = i++)
                {
                    if (((polygon[i].Y > point.Y) != (polygon[j].Y > point.Y)) &&
                    (point.X < (polygon[j].X - polygon[i].X) * (point.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) + polygon[i].X))
                    {
                        isInside = !isInside;
                    }
                }
                return isInside;
            }

这是我认为的源代码 - http://alienryderflex.com/polygon/

2015-03-14 17:15:21
用户4644522
用户4644522

原文:

It turns out that the issue was not the algorithm, but an error elsewhere in my code. It took me a while to figure it out, but once I did the algorithm works perfectly.

翻译:

事实证明问题不在算法上,而是在我代码的其他地方有错误。虽然花了我一段时间才找到错误,但一旦解决了,算法就能完美地工作了。
2015-03-20 15:05:23