Advertisement
karbaev

line-intersection

Mar 8th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. Point* intersection(Point p1, Point p2, Point p3, Point p4) {
  2. // Store the values for fast access and easy
  3. // equations-to-code conversion
  4. float x1 = p1.x, x2 = p2.x, x3 = p3.x, x4 = p4.x;
  5. float y1 = p1.y, y2 = p2.y, y3 = p3.y, y4 = p4.y;
  6.  
  7. float d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  8. // If d is zero, there is no intersection
  9. if (d == 0) return NULL;
  10.  
  11. // Get the x and y
  12. float pre = (x1*y2 - y1*x2), post = (x3*y4 - y3*x4);
  13. float x = ( pre * (x3 - x4) - (x1 - x2) * post ) / d;
  14. float y = ( pre * (y3 - y4) - (y1 - y2) * post ) / d;
  15.  
  16. // Check if the x and y coordinates are within both lines
  17. if ( x < min(x1, x2) || x > max(x1, x2) ||
  18. x < min(x3, x4) || x > max(x3, x4) ) return NULL;
  19. if ( y < min(y1, y2) || y > max(y1, y2) ||
  20. y < min(y3, y4) || y > max(y3, y4) ) return NULL;
  21.  
  22. // Return the point of intersection
  23. Point* ret = new Point();
  24. ret->x = x;
  25. ret->y = y;
  26. return ret;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement