Maths.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /** @format */
  2. export class Line {
  3. public direction: Vector2
  4. public point: Vector2
  5. }
  6. export class Vector2 {
  7. public x: number
  8. public y: number
  9. constructor(x: number = 0, y: number = 0) {
  10. this.x = x
  11. this.y = y
  12. }
  13. public static multiply(vector1: Vector2, vector2: Vector2) {
  14. return vector1.x * vector2.x + vector1.y * vector2.y
  15. }
  16. public static multiply2(scalar: number, vector: Vector2) {
  17. return new Vector2(vector.x * scalar, vector.y * scalar)
  18. }
  19. public static division(vector: Vector2, scalar: number) {
  20. if (scalar == 0) scalar = 1
  21. return new Vector2(vector.x / scalar, vector.y / scalar)
  22. }
  23. public static subtract(vector1: Vector2, vector2: Vector2) {
  24. return new Vector2(vector1.x - vector2.x, vector1.y - vector2.y)
  25. }
  26. public static addition(vector1: Vector2, vector2: Vector2) {
  27. return new Vector2(vector1.x + vector2.x, vector1.y + vector2.y)
  28. }
  29. }
  30. export class RVOMath {
  31. public static readonly RVO_EPSILON = 0.00001
  32. public static readonly RVO_POSITIVEINFINITY = 10000000000000
  33. public static abs(vector: Vector2) {
  34. return this.sqrt(this.absSq(vector))
  35. }
  36. public static absSq(vector: Vector2) {
  37. return Vector2.multiply(vector, vector)
  38. }
  39. public static normalize(vector: Vector2) {
  40. return Vector2.division(vector, this.abs(vector))
  41. }
  42. public static det(vector1: Vector2, vector2: Vector2) {
  43. return vector1.x * vector2.y - vector1.y * vector2.x
  44. }
  45. public static distSqPointLineSegment(vector1: Vector2, vector2: Vector2, vector3: Vector2) {
  46. let r =
  47. Vector2.multiply(Vector2.subtract(vector3, vector1), Vector2.subtract(vector2, vector1)) /
  48. this.absSq(Vector2.subtract(vector2, vector1))
  49. if (r < 0) {
  50. return this.absSq(Vector2.subtract(vector3, vector1))
  51. }
  52. if (r > 1) {
  53. return this.absSq(Vector2.subtract(vector3, vector2))
  54. }
  55. return this.absSq(
  56. Vector2.subtract(
  57. vector3,
  58. Vector2.addition(vector1, Vector2.multiply2(r, Vector2.subtract(vector2, vector1))),
  59. ),
  60. )
  61. }
  62. public static fabs(scalar: number) {
  63. return Math.abs(scalar)
  64. }
  65. public static leftOf(a: Vector2, b: Vector2, c: Vector2) {
  66. return this.det(Vector2.subtract(a, c), Vector2.subtract(b, a))
  67. }
  68. public static sqr(scalar: number) {
  69. return scalar * scalar
  70. }
  71. public static sqrt(scalar: number) {
  72. return Math.sqrt(scalar)
  73. }
  74. public static transfromFloat(value: number) {
  75. return Math.floor(value * 10) / 10
  76. }
  77. }