@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
94 lines (72 loc) • 2.25 kB
JavaScript
import { assert } from "../../../../core/assert.js";
import { BehaviorStatus } from "../BehaviorStatus.js";
import { EntityBehavior } from "./EntityBehavior.js";
/**
* Wait for a given entity event via {@link EntityComponentDataset#addEntityEventListener}
* No failure condition, will wait forever until the event is detected.
* @see SendEventBehavior
* @author Alex Goldring
* @copyright Company Named Limited (c) 2025
*/
export class WaitForEventBehavior extends EntityBehavior {
/**
* Event name
* @type {string}
*/
event = "";
/**
* Has the even occurred already?
* @type {boolean}
*/
detected = false;
/**
* Entity to listen event on
* If value is negative - will assume value of the entity to which the behavior is bound
* @type {number}
*/
target = -1; // TODO replace target with an EntityReference instead for tighter binding
fromJSON({ event, target = -1 }) {
assert.isString(event, 'event');
assert.isInteger(target, 'target');
this.event = event;
this.target = target;
}
/**
*
* @param json
* @return {WaitForEventBehavior}
*/
static fromJSON(json) {
const r = new WaitForEventBehavior();
r.fromJSON(json);
return r;
}
tick(timeDelta) {
if (this.detected) {
return BehaviorStatus.Succeeded;
}
return BehaviorStatus.Running;
}
#listener() {
this.detected = true;
this.ecd.removeEntityEventListener(this.target, this.event, this.#listener, this);
}
initialize(context) {
super.initialize(context);
//reset detection flag
this.detected = false;
if (this.target < 0) {
this.target = this.entity;
}
this.ecd.addEntityEventListener(this.target, this.event, this.#listener, this);
}
finalize() {
super.finalize();
this.ecd.removeEntityEventListener(this.target, this.event, this.#listener, this);
}
}
/**
* @readonly
* @type {string}
*/
WaitForEventBehavior.typeName = "WaitForEventBehavior";