Line intersections for diagonals on a 2d plane in C#

…衆ロ難τιáo~ 提交于 2019-12-24 19:23:48

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11727151/line-intersections-for-diagonals-on-a-2d-plane-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!