LineSegment2D.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace bbiwarg.Utility
  7. {
  8. class LineSegment2D
  9. {
  10. public Vector2D P1 { get; private set; }
  11. public Vector2D P2 { get; private set; }
  12. public Line2D Line { get; private set; }
  13. public float Length { get { return P1.getDistanceTo(P2); }}
  14. public LineSegment2D(Vector2D p1, Vector2D p2)
  15. {
  16. setPoints(p1, p2);
  17. }
  18. private void setPoints(Vector2D p1, Vector2D p2)
  19. {
  20. //endpoints
  21. P1 = p1;
  22. P2 = p2;
  23. //line
  24. Line = new Line2D(P1, P1 - P2);
  25. }
  26. public float getParallelDistanceTo(LineSegment2D line)
  27. {
  28. if (Line.onSide(line.P1) != Line.onSide(line.P2)) return 0;
  29. Vector2D a1 = Line.projectToLine(line.P1);
  30. Vector2D a2 = Line.projectToLine(line.P2);
  31. float distanceA1 = a1.getDistanceTo(line.P1);
  32. float distanceA2 = a2.getDistanceTo(line.P2);
  33. return Math.Min(distanceA1, distanceA2);
  34. }
  35. public float getVerticalDistanceTo(LineSegment2D line)
  36. {
  37. Vector2D a1 = Line.projectToLine(line.P1);
  38. Vector2D a2 = Line.projectToLine(line.P2);
  39. if (P1.isInBox(a1, a2) || P2.isInBox(a1, a2)) return 0;
  40. float distanceP1A1 = P1.getDistanceTo(a1);
  41. float distanceP1A2 = P1.getDistanceTo(a2);
  42. float distanceP2A1 = P2.getDistanceTo(a1);
  43. float distanceP2A2 = P2.getDistanceTo(a2);
  44. return Math.Min(Math.Min(distanceP1A1, distanceP1A2), Math.Min(distanceP2A1, distanceP2A2));
  45. }
  46. public override string ToString()
  47. {
  48. return (int)P1.X + "|" + (int)P1.Y + " --- " + (int)P2.X + "|" + (int)P2.Y;
  49. }
  50. }
  51. }