(Vector2 l1p1, Vector2 l1p2, Vector2 l2p1, Vector2 l2p2)
| 48 | } |
| 49 | |
| 50 | public static Vector2 getIntersection(Vector2 l1p1, Vector2 l1p2, Vector2 l2p1, Vector2 l2p2) { |
| 51 | Vector2 result = new Vector2(); |
| 52 | |
| 53 | // Denominator for ua and ub are the same, so store this calculation |
| 54 | float d = (l2p2.y - l2p1.y) * (l1p2.x - l1p1.x) - (l2p2.x - l2p1.x) * (l1p2.y - l1p1.y); |
| 55 | |
| 56 | //n_a and n_b are calculated as separate values for readability |
| 57 | float n_a = (l2p2.x - l2p1.x) * (l1p1.y - l2p1.y) - (l2p2.y - l2p1.y) * (l1p1.x - l2p1.x); |
| 58 | float n_b = (l1p2.x - l1p1.x) * (l1p1.y - l2p1.y) - (l1p2.y - l1p1.y) * (l1p1.x - l2p1.x); |
| 59 | |
| 60 | // Make sure there is not a division by zero - this also indicates that |
| 61 | // the lines are parallel. |
| 62 | // If n_a and n_b were both equal to zero the lines would be on top of each |
| 63 | // other (coincidental). This check is not done because it is not |
| 64 | // necessary for this implementation (the parallel check accounts for this). |
| 65 | if (d != 0) { |
| 66 | // Calculate the intermediate fractional point that the lines potentially intersect. |
| 67 | float ua = n_a / d; |
| 68 | float ub = n_b / d; |
| 69 | |
| 70 | // The fractional point will be between 0 and 1 inclusive if the lines |
| 71 | // intersect. If the fractional calculation is larger than 1 or smaller |
| 72 | // than 0 the lines would need to be longer to intersect. |
| 73 | if (ua >= 0d && ua <= 1d && ub >= 0d && ub <= 1d) { |
| 74 | result.x = l1p1.x + (ua * (l1p2.x - l1p1.x)); |
| 75 | result.y = l1p1.y + (ua * (l1p2.y - l1p1.y)); |
| 76 | return result; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | //if lines are parallel or don't intersect, just return the midpoint of first line |
| 81 | return getMidpoint(l1p1, l1p2); |
| 82 | } |
| 83 | |
| 84 | public static Vector2 getMidpoint(Vector2 p1, Vector2 p2) { |
| 85 | Vector2 result = new Vector2(); |
no test coverage detected