Line intersections for diagonals on a 2d plane in

2019-09-06 18:19发布

Assume a 2D grid with the top left cell as (0, 0). Pick any two points/coordinates and draw a diagonal and anti-diagonal on each. They may intersect inside or outside the grid.

In the picture attached, the red lines are diagonals to the two points (300, 200) and (700, 800).

How can I find out the coordinates for the diagonal intersections? Also, how would the formula differ if the slope of the line were negative?

I will use this in an algorithm that needs to be highly optimized so the right answer would be the fastest possible way to compute. I'm not sure if this can be done without trignometry.

NOTE: Please keep in mind that the red lines are a true diagonal/anti-diagonal pair. In other words they are at 45 degree angles to the rectangle. This may or may not help select a more optimized formula than vector calculation.

enter image description here

2条回答
放荡不羁爱自由
2楼-- · 2019-09-06 18:38

Let D be the difference between the two side lengths. In your figure, D=200. This is the length of the hypotenuse of the two white triangles (the ones between your exterior intersection points and the rectangle). So the side lengths of those triangles are D/sqrt(2), and so the coordinates of the exterior intersections differ from the rectangle corners by D/2.

Then for your diagram,

(x1,y1) = 300-D/2, 200+D/2 = 200,300
(x2,y2) = 700+D/2, 800-D/2 = 800,700

You'll have to handle all the possible orientations (x1<x2, x1>x2, ...) but they are all symmetric to this one.

查看更多
乱世女痞
3楼-- · 2019-09-06 18:51

It's just math. You have 2 lines with equations

y1 = k1 * x1 + b1
y2 = k2 * x2 + b2
If they intersect then y1 == y2 and x1 = x2 so
k1 * x1 + b1 = k2 * x1 + b2
x1 = (b2 - b1) / (k1 - k2)

The only problem now is how to find k1, k2, b1, b2? Simple! You have 2 points for each line(from graphics.DrawLine(x1, y1, x2, y2)). Use them here. For the first line:

y1 = k * x1 + b
y2 = k * x2 + b
b = y1 - k * x1
y2 = k * x2 + y1 - k * x1 = k * (x2-x1) + y1
so
k = (y2 - y1) / (x2 - x1)

Substitute that k into b = y1-k*x1 and you will get all values you need to calculate exact points of collision.

查看更多
登录 后发表回答