The code

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
/// <summary> /// Gets the coordinates of the intersection point of two lines. /// </summary> /// <param name="A1">A point on the first line.</param> /// <param name="A2">Another point on the first line.</param> /// <param name="B1">A point on the second line.</param> /// <param name="B2">Another point on the second line.</param> /// <param name="found">Is set to false of there are no solution. true otherwise.</param> /// <returns>The intersection point coordinates. Returns Vector2.zero if there is no solution.</returns> public Vector2 GetIntersectionPointCoordinates(Vector2 A1, Vector2 A2, Vector2 B1, Vector2 B2, out bool found) { float tmp = (B2.x - B1.x) * (A2.y - A1.y) - (B2.y - B1.y) * (A2.x - A1.x); if (tmp == 0) { // No solution! found = false; return Vector2.zero; } float mu = ((A1.x - B1.x) * (A2.y - A1.y) - (A1.y - B1.y) * (A2.x - A1.x)) / tmp; found = true; return new Vector2( B1.x + (B2.x - B1.x) * mu, B1.y + (B2.y - B1.y) * mu ); } |

The maths behind To get the point where two lines intersect, we will do some maths. To the mathematicians who will come across this post, I’m truly sorry for the heart attacks or strokes you may experience by reading this post. Ok, let’s take a look on the figure: First, sorry, I […]