@rpgjs/physic
Version:
A deterministic 2D top-down physics library for RPG, sandbox and MMO games
91 lines (90 loc) • 2.28 kB
JavaScript
class CompositeMovement {
/**
* Creates a composite movement.
*
* @param mode - Parallel or sequence execution
* @param strategies - Strategies to aggregate
*/
constructor(mode, strategies) {
this.mode = mode;
this.strategies = strategies;
this.currentIndex = 0;
}
update(body, dt) {
if (this.strategies.length === 0) {
return;
}
if (this.mode === "parallel") {
this.updateParallel(body, dt);
} else {
this.updateSequence(body, dt);
}
}
isFinished() {
if (this.mode === "parallel") {
return this.strategies.length === 0;
}
return this.currentIndex >= this.strategies.length;
}
add(strategy) {
this.strategies.push(strategy);
}
remove(strategy) {
const index = this.strategies.indexOf(strategy);
if (index === -1) {
return false;
}
this.strategies.splice(index, 1);
if (this.currentIndex >= this.strategies.length) {
this.currentIndex = Math.max(0, this.strategies.length - 1);
}
return true;
}
reset() {
this.currentIndex = 0;
}
updateParallel(body, dt) {
const originalVelocity = { x: body.velocity.x, y: body.velocity.y };
let changes = 0;
for (let i = this.strategies.length - 1; i >= 0; i -= 1) {
const strategy = this.strategies[i];
if (!strategy) {
continue;
}
const beforeX = body.velocity.x;
const beforeY = body.velocity.y;
strategy.update(body, dt);
if (beforeX !== body.velocity.x || beforeY !== body.velocity.y) {
changes += 1;
}
if (strategy.isFinished?.()) {
this.strategies.splice(i, 1);
strategy.onFinished?.();
}
}
if (changes > 1) {
body.setVelocity({
x: (body.velocity.x + originalVelocity.x) / 2,
y: (body.velocity.y + originalVelocity.y) / 2
});
}
}
updateSequence(body, dt) {
if (this.currentIndex >= this.strategies.length) {
return;
}
const current = this.strategies[this.currentIndex];
if (!current) {
return;
}
current.update(body, dt);
if (current.isFinished?.()) {
current.onFinished?.();
this.currentIndex += 1;
}
}
}
export {
CompositeMovement
};
//# sourceMappingURL=index32.js.map