@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
61 lines (47 loc) • 1.56 kB
JavaScript
import { assert } from "../../../../core/assert.js";
import { Behavior } from "../Behavior.js";
import { BehaviorStatus } from "../BehaviorStatus.js";
/**
* Single-shot behavior that executes the given function and resolves {@link BehaviorStatus.SUCCESS}
* @template CTX
* @extends {Behavior<CTX>}
* @example
* // will print 'Hello World' in console when executed
* ActionBehavior.from( () => console.log('Hello World') );
* @author Alex Goldring
* @copyright Company Named Limited (c) 2025
*/
export class ActionBehavior extends Behavior {
/**
*
* @param {function(timeDelta:number, context:CTX)} action
* @param {*} [thisArg=this] defaults to behavior itself if not specified
*/
constructor(action, thisArg) {
super();
assert.isFunction(action, "action");
this.__action = action;
if (thisArg === undefined) {
// if thisArg is not supplied, will bind to behavior instead
this.__context = this;
} else {
this.__context = thisArg;
}
}
/**
* Constructor alias
* @returns {ActionBehavior}
*/
static from(func, thisArg) {
return new ActionBehavior(func, thisArg);
}
tick(timeDelta) {
try {
this.__action.call(this.__context, timeDelta, this.context);
return BehaviorStatus.Succeeded;
} catch (e) {
console.warn(e);
return BehaviorStatus.Failed;
}
}
}