Line2D.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. public enum LineSide
  9. {
  10. onLine = 0,
  11. above = 1,
  12. below = 2
  13. }
  14. class Line2D
  15. {
  16. public Vector2D PointOnLine { get; private set; }
  17. public Vector2D Direction { get; private set; }
  18. public Line2D(Vector2D pointOnLine, Vector2D direction) {
  19. PointOnLine = pointOnLine;
  20. Direction = direction.normalize();
  21. }
  22. public float getAngleBetween(Line2D line)
  23. {
  24. float angle = Direction.getAngleBetween(line.Direction);
  25. return Math.Min(angle, 180 - angle);
  26. }
  27. public LineSide onSide(Vector2D point)
  28. {
  29. float yPerX = Direction.Y / Direction.X;
  30. float xDiff = point.X - PointOnLine.X;
  31. float newY = PointOnLine.Y + yPerX * xDiff;
  32. if (newY < point.Y) return LineSide.above;
  33. else if (newY > point.Y) return LineSide.below;
  34. else return LineSide.onLine;
  35. }
  36. public Vector2D projectToLine(Vector2D point)
  37. {
  38. float px = point.X, py = point.Y, dx = Direction.X, dy = Direction.Y, ox = PointOnLine.X, oy = PointOnLine.Y;
  39. float diffx = px - ox;
  40. float diffy = py - oy;
  41. float diff_d = (diffx * dx + diffy * dy);
  42. float d_d = (dx * dx + dy * dy);
  43. float q = diff_d / d_d;
  44. float newX = ox + q * dx;
  45. float newY = oy + q * dy;
  46. return new Vector2D(newX, newY);
  47. }
  48. public Vector2D getIntersection(Line2D line)
  49. {
  50. Vector2D p = PointOnLine;
  51. Vector2D r = Direction;
  52. Vector2D q = line.PointOnLine;
  53. Vector2D s = line.Direction;
  54. float r_cross_s = r.cross(s);
  55. float q_p_cross_s = (q - p).cross(s);
  56. if (r_cross_s == 0.0)
  57. return null;
  58. float t = q_p_cross_s / r_cross_s;
  59. return p + t * r;
  60. }
  61. }
  62. }