1. 1 : import { SteeringBehavior } from '../SteeringBehavior.js';
  2. 2 : import { SeekBehavior } from './SeekBehavior.js';
  3. 3 : import { Vector3 } from '../../math/Vector3.js';
  4. 4 :
  5. 5 : const centerOfMass = new Vector3();
  6. 6 :
  7. 7 : /**
  8. 8 : * This steering produces a steering force that moves a vehicle toward the center of mass of its neighbors.
  9. 9 : *
  10. 10 : * @author {@link https://github.com/Mugen87|Mugen87}
  11. 11 : * @augments SteeringBehavior
  12. 12 : */
  13. 13 : class CohesionBehavior extends SteeringBehavior {
  14. 14 :
  15. 15 : /**
  16. 16 : * Constructs a new cohesion behavior.
  17. 17 : */
  18. 18 : constructor() {
  19. 19 :
  20. 20 : super();
  21. 21 :
  22. 22 : // internal behaviors
  23. 23 :
  24. 24 : this._seek = new SeekBehavior();
  25. 25 :
  26. 26 : }
  27. 27 :
  28. 28 : /**
  29. 29 : * Calculates the steering force for a single simulation step.
  30. 30 : *
  31. 31 : * @param {Vehicle} vehicle - The game entity the force is produced for.
  32. 32 : * @param {Vector3} force - The force/result vector.
  33. 33 : * @param {Number} delta - The time delta.
  34. 34 : * @return {Vector3} The force/result vector.
  35. 35 : */
  36. 36 : calculate( vehicle, force /*, delta */ ) {
  37. 37 :
  38. 38 : centerOfMass.set( 0, 0, 0 );
  39. 39 :
  40. 40 : const neighbors = vehicle.neighbors;
  41. 41 :
  42. 42 : // iterate over all neighbors to calculate the center of mass
  43. 43 :
  44. 44 : for ( let i = 0, l = neighbors.length; i < l; i ++ ) {
  45. 45 :
  46. 46 : const neighbor = neighbors[ i ];
  47. 47 :
  48. 48 : centerOfMass.add( neighbor.position );
  49. 49 :
  50. 50 : }
  51. 51 :
  52. 52 : if ( neighbors.length > 0 ) {
  53. 53 :
  54. 54 : centerOfMass.divideScalar( neighbors.length );
  55. 55 :
  56. 56 : // seek to it
  57. 57 :
  58. 58 : this._seek.target = centerOfMass;
  59. 59 : this._seek.calculate( vehicle, force );
  60. 60 :
  61. 61 : // the magnitude of cohesion is usually much larger than separation
  62. 62 : // or alignment so it usually helps to normalize it
  63. 63 :
  64. 64 : force.normalize();
  65. 65 :
  66. 66 : }
  67. 67 :
  68. 68 : return force;
  69. 69 :
  70. 70 : }
  71. 71 :
  72. 72 : }
  73. 73 :
  74. 74 : export { CohesionBehavior };