private static bool CalcLinesIntersection(CurveSegment2D segment1, CurveSegment2D segment2, out Vector2 intersection, float angleLimit) {//计算两线交点 intersection = Vector2.zero; Vector2 p1 = segment1.point1; Vector2 p2 = segment1.point2; Vector2 p3 = segment2.point1; Vector2 p4 = segment2.point2; float denominator = (p2.y - p1.y) * (p4.x - p3.x) - (p1.x - p2.x) * (p3.y - p4.y); if (denominator == 0) {//如果分母为0,则表示平行 return(false); } float angle = Vector2.Angle(segment1.SegmentVector, segment2.SegmentVector); // 检查段之间的角度 if (angle < angleLimit || (180f - angle) < angleLimit) {//如果两个段之间的角度太小,我们将它们视为平行 return(false); } float x = ((p2.x - p1.x) * (p4.x - p3.x) * (p3.y - p1.y) + (p2.y - p1.y) * (p4.x - p3.x) * p1.x - (p4.y - p3.y) * (p2.x - p1.x) * p3.x) / denominator; float y = -((p2.y - p1.y) * (p4.y - p3.y) * (p3.x - p1.x) + (p2.x - p1.x) * (p4.y - p3.y) * p1.y - (p4.x - p3.x) * (p2.y - p1.y) * p3.y) / denominator; intersection.Set(x, y); return(true); }
private bool TryCalculateLinesIntersection(CurveSegment2D segment1, CurveSegment2D segment2, out Vector2 intersection, float angleLimit) { intersection = new Vector2(); Vector2 p1 = segment1.point1; Vector2 p2 = segment1.point2; Vector2 p3 = segment2.point1; Vector2 p4 = segment2.point2; float denominator = (p2.y - p1.y) * (p4.x - p3.x) - (p1.x - p2.x) * (p3.y - p4.y); // If denominator is 0, means parallel if (denominator == 0) { return(false); } // Check angle between segments float angle = Vector2.Angle(segment1.SegmentVector, segment2.SegmentVector); // if the angle between two segments is too small, we treat them as parallel if (angle < angleLimit || (180f - angle) < angleLimit) { return(false); } float x = ((p2.x - p1.x) * (p4.x - p3.x) * (p3.y - p1.y) + (p2.y - p1.y) * (p4.x - p3.x) * p1.x - (p4.y - p3.y) * (p2.x - p1.x) * p3.x) / denominator; float y = -((p2.y - p1.y) * (p4.y - p3.y) * (p3.x - p1.x) + (p2.x - p1.x) * (p4.y - p3.y) * p1.y - (p4.x - p3.x) * (p2.y - p1.y) * p3.y) / denominator; intersection.Set(x, y); return(true); }