# 2D线线相交功能不起作用

WDUK

``````//https://en.m.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line
public static bool LineLineIntersectionInfinite(Vector2 line1Point1, Vector2 line1Point2, Vector2 line2Point1, Vector2 line2Point2, out Vector2 intersectionPoint)
{
// define the out parameter
intersectionPoint = Vector2.zero;

//1 = line1Point1
//2 = line1Point2
//3 = line2Point1
//4 = line2Point2

var x1 = line1Point1.x;
var x2 = line1Point2.x;
var x3 = line2Point1.x;
var x4 = line2Point2.x;

var y1 = line1Point1.y;
var y2 = line1Point2.y;
var y3 = line2Point1.y;
var y4 = line2Point2.y;

var x1Minusx2 = x1 - x2;
var x3Minusx4 = x3 - x4;
var y1Minusy2 = y1 - y2;
var y3Minusy4 = y3 - y4;

var denominator = x1Minusx2 * y3Minusy4 - y1Minusy2 * x3Minusx4;

if (Mathf.Approximately(denominator, 0)) return false;

var a = (x1 * y2 - y1 * x2);
var b = (x3 * y4 - y3 * x4);
var ax3MinusX4 = a * x3Minusx4;

//x
var numerator = ax3MinusX4 - x1Minusx2 * b;
var x = numerator / denominator;

//y
numerator = ax3MinusX4 - y1Minusy2 * b;
var y = numerator / denominator;

intersectionPoint = new Vector2(x, y);

return true;
}
``````

``````line1point1 = (2.6, -1.4)
line1point2 = (3.6,-1.3)

line2point1 = (3.5,2.0)
line2point2 = (3.9,1.1)

Gives intersection result: (5.1,1.0)
``````

`x1Minusx2` == -1.00

`x3Minusx4` == -0.40

`y1Minusy2` == -0.10

`y3Minusy4` == 0.90

`denominator` == -0.94

`a`== 1.66

`b`== -3.95

`ax3MinusX4` == -0.664

`numerX`== -4.614

`x`== 4.908510638

`ay3minusy4`== 1.494

`numerY`== 1.099

`y`== -1.169148936

0 条评论