Vector2D.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 Vector2D
  9. {
  10. public float x;
  11. public float y;
  12. public Vector2D(float x, float y) {
  13. this.x = x;
  14. this.y = y;
  15. }
  16. public float getLength() {
  17. return (float) Math.Sqrt(x * x + y * y);
  18. }
  19. public float getDistanceTo(Vector2D vector) {
  20. float xDiff = x - vector.x;
  21. float yDiff = y - vector.y;
  22. return (float)Math.Sqrt(xDiff * xDiff + yDiff * yDiff);
  23. }
  24. public float getMinAngleBetween(Vector2D vector) {
  25. float angle = getAngleBetween(vector);
  26. if (angle > Math.PI/2)
  27. return (float) (Math.PI - angle);
  28. else
  29. return angle;
  30. }
  31. public float getAngleBetween(Vector2D vector) {
  32. return (float)Math.Acos(dotProduct(vector) / (getLength() * vector.getLength()));
  33. }
  34. public float dotProduct(Vector2D vector) {
  35. return x * vector.x + y * vector.y;
  36. }
  37. public static Vector2D projectToLine(Vector2D point, Vector2D direction, Vector2D pointOnLine) {
  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 static Vector2D operator *(float scalar, Vector2D vector)
  49. {
  50. return new Vector2D(scalar * vector.x, scalar * vector.y);
  51. }
  52. public static Vector2D operator +(Vector2D vector1, Vector2D vector2)
  53. {
  54. return new Vector2D(vector1.x + vector2.x, vector1.y + vector2.y);
  55. }
  56. public static Vector2D operator -(Vector2D vector1, Vector2D vector2)
  57. {
  58. return new Vector2D(vector1.x - vector2.x, vector1.y - vector2.y);
  59. }
  60. }
  61. }