Paa*_*pan 16 graphics geometry
给定线段,即两个点(x1,y1)和(x2,y2),一个点P(x,y)和角度θ.我们如何找到这条线段和从水平方向θ角度θ发出的线光线是否相交?如果它们相交,如何找到交点?
以下是其他答案中给出的算法的C#代码:
/// <summary>
/// Returns the distance from the ray origin to the intersection point or null if there is no intersection.
/// </summary>
public double? GetRayToLineSegmentIntersection(Point rayOrigin, Vector rayDirection, Point point1, Point point2)
{
var v1 = rayOrigin - point1;
var v2 = point2 - point1;
var v3 = new Vector(-rayDirection.Y, rayDirection.X);
var dot = v2 * v3;
if (Math.Abs(dot) < 0.000001)
return null;
var t1 = Vector.CrossProduct(v2, v1) / dot;
var t2 = (v1 * v3) / dot;
if (t1 >= 0.0 && (t2 >= 0.0 && t2 <= 1.0))
return t1;
return null;
}
Run Code Online (Sandbox Code Playgroud)