Line2D.cs 2.1 KB

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