silphius/app/ecs/components/alive.js
2024-09-17 01:25:39 -05:00

54 lines
1.3 KiB
JavaScript

import Component from '@/ecs/component.js';
export default class Alive extends Component {
instanceFromSchema() {
const {ecs} = this;
return class AliveInstance extends super.instanceFromSchema() {
$$dead = false;
acceptDamage(amount) {
const health = Math.min(this.maxHealth, Math.max(0, this.health + amount));
this.health = health;
if (0 === health) {
this.die();
}
}
die() {
if (this.$$dead) {
return;
}
this.$$dead = true;
const {Ticking} = ecs.get(this.entity);
if (Ticking) {
this.$$death.context.entity = ecs.get(this.entity);
const ticker = this.$$death.ticker();
ecs.addDestructionDependency(this.entity.id, ticker);
Ticking.add(ticker);
}
}
};
}
async load(instance) {
// heavy handed...
if ('undefined' !== typeof window) {
return;
}
instance.$$death = await this.ecs.readScript(
instance.deathScript,
{
ecs: this.ecs,
},
);
if (0 === instance.maxHealth) {
instance.maxHealth = instance.health;
}
}
static properties = {
deathScript: {
defaultValue: '/resources/misc/death-default.js',
type: 'string',
},
health: {type: 'uint32'},
maxHealth: {type: 'uint32'},
};
}