import { Utils } from "../utils/index.js"
import { Vector2 } from "../math/index.js"
/**
* Manages the behaviours for an agent.
*
* @package
*/
export class BehaviourManager {
/**
* A list of behaviors
*
* @type Behaviour[]
*/
_behaviours = []
/**
* Accumulated force from behaviours to apply to agent
*/
_accumulated = new Vector2()
/**
* Adds a behavior to the manager
*
* @param {Behaviour} behaviour
*/
add(behaviour) {
this._behaviours.push(behaviour)
if (this.active) behaviour.init(this._agent)
}
/**
* Removes a behavior to the manager
*
* @param {Behaviour} behaviour
*/
remove(behaviour) {
Utils.removeElement(this._behaviours, this._behaviours.indexOf(behaviour))
}
/**
* Boots up the behavoiurs of the agent that contains it.
*
* @param {Agent} agent
*/
init(agent) {
this._agent = agent
for (var i = 0; i < this._behaviours.length; i++) {
this._behaviours[i].init(agent)
}
}
/**
* Updates the behaviours of the agent and applies changes to agent.
*
* @param {number} inv_dt
*/
update(inv_dt) {
let result = new Vector2()
this._accumulated.set(0, 0)
for (let i = 0; i < this._behaviours.length; i++) {
this._behaviours[i].calc(result, inv_dt)
this._accumulated.add(result)
}
this._agent.acceleration.add(this._accumulated)
this._agent.orientation.value = Vector2.toRad(this._agent.velocity)
}
/**
* Removes all behaviours from a manager.
*/
clear() {
Utils.clearArr(this._behaviours)
}
/**
* @ignore
* Used for visually debugging items.
*/
draw(renderer) {
this._behaviours.forEach(b => b.draw(renderer))
}
}