GMLscripts.com

lines_intersect

lines_intersect(x1, y1, x2, y2, x3, y3, x4, y4, segment)
Returns a scalar (t) that indicates if two lines or segments intersect.
COPY
  1. /// @func lines_intersect(x1, y1, x2, y2, x3, y3, x4, y4, segment)
  2. ///
  3. /// @desc Returns a scalar (t) that indicates if two lines or segments intersect.
  4. /// A value of (0 < t <= 1) indicates an intersection within the line segment,
  5. /// a value of 0 indicates no intersection, other values indicate an
  6. /// intersection beyond the endpoints.
  7. ///
  8. /// The two lines are given by end point coordinate pairs.
  9. /// The first line is {x1,y1}->{x2,y2}, the second is {x3,y3}->{x4,y4}.
  10. ///
  11. /// @param {real} x1
  12. /// @param {real} y1
  13. /// @param {real} x2
  14. /// @param {real} y2
  15. /// @param {real} x3
  16. /// @param {real} y3
  17. /// @param {real} x4
  18. /// @param {real} y4
  19. /// @param {boolean} segment if true, confine test to line segments
  20. ///
  21. /// @return {real} point of intersection
  22. ///
  23. /// Note: By substituting the return value (t) into the parametric form
  24. /// of the first line, the point of intersection can be determined.
  25. /// eg. x = x1 + t * (x2 - x1)
  26. /// y = y1 + t * (y2 - y1)
  27. ///
  28. /// GMLscripts.com/license
  29.  
  30. function lines_intersect(x1, y1, x2, y2, x3, y3, x4, y4, segment)
  31. {
  32. var ua, ub, ud, ux, uy, vx, vy, wx, wy;
  33. ua = 0;
  34. ux = x2 - x1;
  35. uy = y2 - y1;
  36. vx = x4 - x3;
  37. vy = y4 - y3;
  38. wx = x1 - x3;
  39. wy = y1 - y3;
  40. ud = vy * ux - vx * uy;
  41. if (ud != 0)
  42. {
  43. ua = (vx * wy - vy * wx) / ud;
  44. if (segment)
  45. {
  46. ub = (ux * wy - uy * wx) / ud;
  47. if (ua < 0 || ua > 1 || ub < 0 || ub > 1) ua = 0;
  48. }
  49. }
  50. return ua;
  51. }

Contributors: xot

GitHub: View · Commits · Blame · Raw