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.
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 areD/sqrt(2)
, and so the coordinates of the exterior intersections differ from the rectangle corners byD/2
.Then for your diagram,
You'll have to handle all the possible orientations (
x1<x2
,x1>x2
, ...) but they are all symmetric to this one.It's just math. You have 2 lines with equations
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:
Substitute that
k
intob = y1-k*x1
and you will get all values you need to calculate exact points of collision.