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