pathCursor.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { Vector3 } from "../Maths/math.vector.js";
  2. /**
  3. * A cursor which tracks a point on a path
  4. */
  5. export class PathCursor {
  6. /**
  7. * Initializes the path cursor
  8. * @param _path The path to track
  9. */
  10. constructor(_path) {
  11. this._path = _path;
  12. /**
  13. * Stores path cursor callbacks for when an onchange event is triggered
  14. */
  15. this._onchange = new Array();
  16. /**
  17. * The value of the path cursor
  18. */
  19. this.value = 0;
  20. /**
  21. * The animation array of the path cursor
  22. */
  23. this.animations = [];
  24. }
  25. /**
  26. * Gets the cursor point on the path
  27. * @returns A point on the path cursor at the cursor location
  28. */
  29. getPoint() {
  30. const point = this._path.getPointAtLengthPosition(this.value);
  31. return new Vector3(point.x, 0, point.y);
  32. }
  33. /**
  34. * Moves the cursor ahead by the step amount
  35. * @param step The amount to move the cursor forward
  36. * @returns This path cursor
  37. */
  38. moveAhead(step = 0.002) {
  39. this.move(step);
  40. return this;
  41. }
  42. /**
  43. * Moves the cursor behind by the step amount
  44. * @param step The amount to move the cursor back
  45. * @returns This path cursor
  46. */
  47. moveBack(step = 0.002) {
  48. this.move(-step);
  49. return this;
  50. }
  51. /**
  52. * Moves the cursor by the step amount
  53. * If the step amount is greater than one, an exception is thrown
  54. * @param step The amount to move the cursor
  55. * @returns This path cursor
  56. */
  57. move(step) {
  58. if (Math.abs(step) > 1) {
  59. // eslint-disable-next-line no-throw-literal
  60. throw "step size should be less than 1.";
  61. }
  62. this.value += step;
  63. this._ensureLimits();
  64. this._raiseOnChange();
  65. return this;
  66. }
  67. /**
  68. * Ensures that the value is limited between zero and one
  69. * @returns This path cursor
  70. */
  71. _ensureLimits() {
  72. while (this.value > 1) {
  73. this.value -= 1;
  74. }
  75. while (this.value < 0) {
  76. this.value += 1;
  77. }
  78. return this;
  79. }
  80. /**
  81. * Runs onchange callbacks on change (used by the animation engine)
  82. * @returns This path cursor
  83. */
  84. _raiseOnChange() {
  85. this._onchange.forEach((f) => f(this));
  86. return this;
  87. }
  88. /**
  89. * Executes a function on change
  90. * @param f A path cursor onchange callback
  91. * @returns This path cursor
  92. */
  93. onchange(f) {
  94. this._onchange.push(f);
  95. return this;
  96. }
  97. }
  98. //# sourceMappingURL=pathCursor.js.map